首页 > 语言 > JavaScript > 正文

详解vue2.0组件通信各种情况总结与实例分析

2024-05-06 15:19:31
字体:
来源:转载
供稿:网友

Props在vue组件中各种角色总结

在Vue中组件是实现模块化开发的主要内容,而组件的通信更是vue数据驱动的灵魂,现就四种主要情况总结如下:

使用props传递数据---组件内部

//html<div id="app1">  <i>注意命名规定:仅在html内使用my-message</i>  <child my-message="组件内部数据传递"></child></div>//js<script>  Vue.component('child', {    props: ['myMessage'],    template: '<mark>{{ myMessage }}<mark/>'  });  new Vue({    el: '#app1'  })</script>

动态props通信---组件与根节点(父子之间)

<div id="app2">  <input v-model="parentMsg">  <br>  <child :parent-msg="parentMsg"></child></div><script>  Vue.component('child', {    props: ['parentMsg'],    template: '<mark>{{ parentMsg }}<mark/>'  });  new Vue({    el: '#app2',    data: {      parentMsg: 'msg from parent!'    }  })</script>

对比分析:

例子1:

<comp some-prop="1"></comp>//组件内部数据传递,对应字面量语法:传递了一个字符串"1" 

例子2:

<comp v-bind:some-prop="1"></comp>//组件与根节点数据传递,对应动态语法:传递实际的数字:js表达式 

单向数据流动特点:父组件属性变化时将传导给子组件,反之不可

两种改变prop情况

注意在 JavaScript 中对象和数组是引用类型,指向同一个内存空间,如果 prop 是一个对象或数组,在子组件内部改变它会影响父组件的状态。

//定义一个局部data属性,并将 prop 的初始值作为局部数据的初始值props: ['initialCounter'],    data: function () {    return { counter: this.initialCounter }    }//定义一个局部computed属性,此属性从 prop 的值计算得出 props: ['size'],    computed: {    normalizedSize: function () {    return this.size.trim().toLowerCase()    }    }

子组件索引

尽管有 props 和 events ,但是有时仍然需要在 JavaScript 中直接访问子组件。为此可以使用 ref 为子组件指定一个索引 ID

<div id="parent"><!-- vm.$refs.p will be the DOM node --><b ref="p">hello</b><!-- vm.$refs.child will be the child comp instance --><user-profile v-for='i in 3' ref="profile"></user-profile></div><script>var userPf=Vue.component('user-profile',{  template:'<div>hello $refs</div>'});var parent = new Vue({ el: '#parent' });// 访问子组件var child = parent.$refs.profile;console.log(child[0]);console.log(parent.$refs.p);</script>

$refs 只在组件渲染完成后才填充,并且它是非响应式的。它仅仅作为一个直接访问子组件的应急方案——应当避免在模版或计算属性中使用 $refs 。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选