2019 年 5 月 28 日 23:25
4-1 组件注意的细节
组件里的 data 必须是个函数 return {}
ref 的两种情况
非组件 : this.$refs.xxx 获取的是 dom
组件里 : this.$refs.xxx 获取的是子组件的引用
4-2 父子组件传递
图片来源慕课网 侵权删
父子组件
非父子组件 vuex 解决 学习成本高
爷孙组件
兄弟组件
- <!DOCTYPE html>
- <HTML>
- <head>
- <title>
- test for vue
- </title>
- <script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js">
- </script>
- </head>
- <body>
- <div id="app">
- <h3>
- 非父子组件间传值 (Bus / 总线 / 发布订阅模式 / 观察者模式)
- </h3>
- <child content="Dad gives u">
- </child>
- <child content="This money">
- </child>
- </div>
- <script type="text/javascript">
- // 非父子组件 用总线机制 其实就是给 vue 挂了个全局的属性
- Vue.prototype.bus = new Vue() Vue.component('child', {
- props: {
- content: String
- },
- template: '<div @click="handleClick">{{content}}</div>',
- methods: {
- handleClick() {
- // alert(this.content)
- this.bus.$emit('explode_func', this.content)
- }
- },
- mounted: function() {
- var _that = this this.bus.$on('explode_func',
- function(msg) {
- alert(msg) // 这里会跳出两次 以为组件有两个 都监听了方法
- _that.content = msg
- })
- }
- }) var App = new Vue({
- el: "#app"
- })
- </script>
- </body>
- </HTML>
报错
其实就是单向数据流 - 子组件不能修改父组件传递过来的值 所以 data 里做个 copy 就好了
- Vue.prototype.bus = new Vue()
- Vue.component('child',{
- props:{
- content:String
- },
- data(){
- return {
- selfContent:this.content
- }
- },
- template:'<div @click="handleClick">{{selfContent}}</div>',
- methods:{
- handleClick(){
- // alert(this.content)
- this.bus.$emit('explode_func',this.selfContent)
- }
- },
- mounted:function(){
- var _that = this
- this.bus.$on('explode_func',function(msg){
- alert(msg) // 这里会跳出两次 以为组件有两个 都监听了方法
- _that.selfContent = msg
- })
- }
- })
- var App = new Vue({
- el:"#app"
- })
发布订阅 / 观察者模式 这两个模式 其实小程序写多了自然就特别容易理解
其实还是得理解 暴露函数 跟监听函数 也就是子传父的理解 多写写练练 就熟悉了
来源: http://www.jianshu.com/p/21c8ef30532c