〖Vue〗必备小知识一 Vue组件及组件传值

218 阅读1分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

本文已参与「掘力星计划」,赢取创作大礼包,挑战创作激励金。

Vue 组件 component

组件是可复用的 Vue 实例, 且带有一个名字, 可分为全局组件和局部组件

  • 全局组件

  • 局部注册的的组件

  • 组件里的数据要独立的

组件间传值

父组件给子组件传值 props

父组件 -> 子组件: 父组件绑定 propName -> 子组件用 props 接收

  1. 对象形式 props:
props: {
  属性: {
    type: required,
    default
  }
}
  1. 数组形式: props: ["父组件的属性",.....]
  • created() 在实例创建完成后被立即调用

单向数据流

数据由父组件传给子组件, 且不能更改, 修改其值则会警示信息 [Vue warn], 如下

vue.js:597 [Vue warn]: Avoid mutating a prop directly since the value will be
overwritten whenever the parent component re-renders. Instead, use a data or 
computed property based on the prop's value. Prop being mutated: "n"

全局组件 和 局部组件

<script>
  // 全局组件
  Vue.component("testComponent", {
    template: "<div>test component</div>"
  })

  // 局部注册的组件
  var obj = { property: 666 }
  var localCom = {
    template: "<div v-on:click=\"inc\">localCom component {{ property }}</div>",
    data() {
      // 组件中的数据时一个 data 函数, 并且返回一个对象. 这样保证每个组件实例的数据都是独立的
      return {
        property: 777,
      }
    },
    methods: {
      inc() {
        this.property++
      }
    }
  }
  new Vue({
    el: "#box",
    components: { // 注册局部组件
      localCom
    }
  })
</script>

<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.5.6/vue.js"></script>
<body>
    <div>
      root component
      <br/>
      <test-component></test-component>
      <test-component></test-component>
      <test-component></test-component>
      <test-component></test-component>
      <test-component></test-component>
      <local-com></local-com>
      <local-com></local-com>
      <local-com></local-com>
      <local-com></local-com>
      <local-com></local-com>
    </div>
    <hr/>
    <div id="box2">
      <test-component></test-component>
    </div>
  </body>
</script>

子组件给父组件传值

子组件给父组件传递数据, 处理顺序:

  1. this.$emit(“事件的名称”, 传递的值)

  2. 监听 v-on:事件的名称=”事件处理函数”

  3. 父组件的 methods里, 用事件处理函数的参数就可以拿到子组件传递过来的值

  4. 对接收到的值进行处理