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

 

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 。

数据反传---自定义事件

自定义事件的根基在于每个vue实例都实现了事件接口(Event interface)
Vue的事件系统分离自浏览器的EventTarget API。尽管它们的运行类似,但是$on 和 $emit 不是addEventListener 和 dispatchEvent 的别名。
父组件可以在使用子组件的地方直接用 v-on 来监听子组件触发的事件

  • 监听:$on(eventName)
  • 触发:$emit(eventName)

    <div id="app3">
    <p>Look at the parent's data: <mark>{{t}}</mark> & the child's data: <mark>{{childWords}}</mark></p>
    <child v-on:add="pChange"></child>
    <child v-on:add="pChange"></child>
    <child v-on:click.native="native"></child>
    </div>
    <script>
    Vue.component('child', {
    template: `<button @click="add">{{ c }}</button>`,
    data: function () {
    return {
    c: 0,
    msg: 'I am from child\'s data'
    }
    },
    methods: {
    add: function () {
    this.c += 1;
    this.$emit('add',this.msg);
    }
    },
    });
    new Vue({
    el: '#app3',
    data: {
    t: 0,
    childWords: ''
    },
    methods: {
    pChange: function (msg) {
    this.t += 1;
    this.childWords=msg;
    },
    native:function () {
    alert('I am a native event ,which comes from the root element!');
    }
    }
    })
    </script>

    兄弟间通信---简单场景用bus,复杂场景用vuex

<div id="app4">
<display></display>
<increment></increment>
</div>
<script>
var bus = new Vue();
Vue.component('increment', {
template: `<button @click="add">+</button>`,
data: function () {
return {count: 0}
},
methods: {
add: function () {
bus.$emit('inc', this.count+=1)
}
}
});
Vue.component('display', {
template: `<span>Clicked: <mark>{{c}}</mark> times</span>`,
data: function () {
return {c: 0}
},
created: function () {
var self=this;
// bus.$on('inc', function (num) {
// self.c = num
// });
bus.$on('inc', (num) =>
this.c = num
);
}
});
vm = new Vue({
el: "#app4",
})
</script>

总结:Vue中关于组件间及组件与根节点间通信都可以人为是父子兄弟间的通信,另外父子关系是相对的即与上下文有关(比如A组件的父组件可能是B组件的子组件);上述四个例子分别演示了不同组件通信的机制。
澄清了上述问题不难理这句话:
编译作用域---父组件模板的内容在父组件作用域内编译;子组件模板的内容在子组件作用域内编译。分发内容是在父组件作用域内编译

 

通信vue2.0组件的更多相关文章

  1. vue2.0组件传值

    props down   emit up 嘿嘿    如果是第一次接触vue2.0组件传值的肯定很疑惑,这是什么意思(大神总结的,我也就是拿来用用) “down”—>指的是下的意思,即父组件向子 ...

  2. vue2.0组件库

    UI组件 element - 饿了么出品的Vue2的web UI工具套件 Vux - 基于Vue和WeUI的组件库 mint-ui - Vue 2的移动UI元素 iview - 基于 Vuejs 的开 ...

  3. Vue2.0组件之间通信(转载)

    Vue中组件这个特性让不少前端er非常喜欢,我自己也是其中之一,它让前端的组件式开发更加合理和简单.笔者之前有写过一篇Vue2.0子父组件通信,这次我们就来聊一聊平级组件之间的通信. 首先我们先搭好开 ...

  4. Vue2.0组件之间通信

    Vue中组件这个特性让不少前端er非常喜欢,我自己也是其中之一,它让前端的组件式开发更加合理和简单.笔者之前有写过一篇Vue2.0子父组件通信,这次我们就来聊一聊平级组件之间的通信. 首先我们先搭好开 ...

  5. Vue2.0组件实现动态搜索引擎(一)

    原文链接:https://blog.csdn.net/qwezxc24680/article/details/74550556 从github上看到一个不错的开源项目:https://github.c ...

  6. Vue2.0组件间数据传递

    Vue1.0组件间传递 使用$on()监听事件: 使用$emit()在它上面触发事件: 使用$dispatch()派发事件,事件沿着父链冒泡: 使用$broadcast()广播事件,事件向下传导给所有 ...

  7. Vue2.0+组件库总结

    转自:https://blog.csdn.net/lishanleilixin/article/details/84025459 UI组件 element - 饿了么出品的Vue2的web UI工具套 ...

  8. 转:Vue2.0+组件库总结

    UI组件 element - 饿了么出品的Vue2的web UI工具套件 Vux - 基于Vue和WeUI的组件库 mint-ui - Vue 2的移动UI元素 iview - 基于 Vuejs 的开 ...

  9. Vue2.0组件的继承与扩展

    如果有需要源代码,请猛戳源代码 希望文章给大家些许帮助和启发,麻烦大家在GitHub上面点个赞!!!十分感谢 前言 本文将介绍vue2.0中的组件的继承与扩展,主要分享slot.mixins/exte ...

随机推荐

  1. Sharepoint学习笔记—习题系列--70-573习题解析 -(Q32-Q34)

    Question 32You create a custom Web Part.You need to ensure that a custom property is visible in Edit ...

  2. java多线程系列7-停止线程

    本文主要总结在java中停止线程的方法 在java中有以下三种方法可以终止正在运行的线程: 1.使用退出标志 2.使用stop方法强行终止线程,但是不推荐,因为stop和suspend.resume一 ...

  3. clang: error: no such file or directory: xxx.pch

    今天打开一个下载的例子 报clang: error: no such file or directory: xxx.pch的错 说一下解决方案 1.先在你的工程里找到这.pch文件- 2.把它现在的路 ...

  4. 关于报malformed or corrupted AST file: 'Unable to load module 的错~

    今天早上 一运行程序 居然报错,我都惊呆了,昨天明明好好的-但是百度是强大的- 报错内容: malformed or corrupted AST file: 'Unable to load modul ...

  5. win7操作技巧

    Q : 打开文件夹默认最大化A :随便打开一个文件夹 鼠标移动到左上角 然后点击鼠标左键 选择“最大化” 后关闭 之后每次打开就是最大化了

  6. 为什么需要SQL Profile

    为什么需要SQL Profile Why oracle need SQL Profiles,how it work and what are SQL Profiles... 使用DBMS_XPLAN. ...

  7. spring中的 classpath* 存在可移植性问题

    classpath* 的可移植性问题,许多人都应该遇到过了.下面就是一个例子(使用的是spring4.1.5和mybatis3.2.8): <bean id="sqlSessionFa ...

  8. redis客户端--jedis

    一.jedis jedis 是 redis推荐的java客户端.通过Jedis我们可以很方便地使用java代码的方式,对redis进行操作.jedis使用起来比较简单,它的操作方法与redis命令相类 ...

  9. js获取页面传过来的参数

    //接收页面传过来的值 //RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i" ...

  10. cocos2d-x之初试内存管理机制

    bool HelloWorld::init() { if ( !Layer::init() ) { return false; } Size visibleSize = Director::getIn ...