inheritAttrs 和 attrs

/*
 * 目录结构:
 *                           child.vue(子组件)
 *  components--> Child-->
 *                           child2.vue(子子组件)
 *
 *  pages-->parent.vue(父组件)
 */

// 父组件
<template>
  <div v-color>
    <child :value="text" :count="count"></child>
  </div>
</template>
<script>
import child from "../components/Child/child";
export default {
  data() {
    return {
      text: "父组建值",
      count: 66666
    };
  },
  provide() {
    return {
      parent: this
    };
  },
  components: {
    child
  }
};
</script>

// 子组件 child.vue
<template>
  <div>
    <my-child v-bind="$attrs"></my-child>
  </div>
</template>
<script>
import myChild from "./child2";
export default {
  props: {
    value: {
      type: String,
      default: ""
    }
  },
  inheritAttrs: false, // 让传递给子组建的值隐藏,F12查看原本在dom上存在count="66666"标示,加上后可以在dom上不显示
  components: {
    myChild
  },
  mounted() {
    console.log(this.$attrs);
  }
};
</script>

// 子子组件 child2.vue
<template>
  <div>我是最子子组建:{{$attrs.count}}</div>
</template>
<script>
export default {
  mounted() {
    console.log("22222:", this.$attrs) // 可以跨组件获取祖先级传入的值
  }
};
</script>

provide 和 inject

// 父组件 parent.vue 非响应写法
<template>
  <div>
    <child></child>
  </div>
</template>
<script>
import child from "../components/Child/child";
export default {
  data() {
    return {
    };
  },
  provide: {
    parent: '父组建值'
  },
  components: {
    child
  }
};
</script>

// 组件child.vue 引用 child2.vue(省略)
// 子子组件child2.vue
<template>
  <div>我是子子组建:{{this.parent}}</div>
</template>
<script>
export default {
  mounted() {
    console.log("另外一种传值方式:", this.parent);
  },
  inject: ["parent"]
};
</script>


// 父组件 parent.vue 响应写法
<template>
  <div v-color>
    <child :value="test" :count="count"></child>
  </div>
</template>
<script>
import child from "../components/Child/child";
export default {
  data() {
    return {
        text: ''
    };
  },
  provide() {
    return {
      parent: this
    };
  },
  components: {
    child
  }
};
</script>

// 组件child.vue 引用 child2.vue(省略)
// 子子组件child2.vue
<template>
  <div>我是子子组建:{{this.parent.text}}</div>
</template>
<script>
export default {
  mounted() {
    console.log("另外一种传值方式:", this.parent);
    this.parent.text = "卧槽,无情"; // 可以改变父级状态值并更新页面
  },
  inject: ["parent"]
};
</script>
posted on 2020-03-26 16:14  佑之以航  阅读(1218)  评论(0编辑  收藏  举报