Sons routing VUE- traditional values and change values (controls show hidden)
- A: from father to son, an event dispatcher, the child call the parent method
Father route
<Input @changedFn="toggle"></Input> // 组件
data () {
return {
isShow: false
}
},
methods: {
toggle () { // 父组件写了一个方法,子组件来调用
this.isShow = true
}
},
Sub-routing
<input @click="changed" readonly type="text">
methods: {
changed () {
this.$emit('changedFn', true) // 事件派发:参数一:事件名 参数二:传递的值(可不写)
}
}
- II: from father to son change values, synchronization parent
Father route
<Input :subIsShow.sync="isShow"></Input>
// .sync是同步的意思,是用来子路由修改父路由传过来的值,父路由也同步修改
// 子路由定义了一个subIsShow参数来接受父路由isShow传递的值
data () {
return {
isShow: false
}
},
Sub-routing
<input @click="changed" readonly type="text">
props: { // 子路由在changed方法里定义了subIsShow用来接收父路由传过来的isShow的值
subIsShow: {
type: Boolean, // 做类型判断
default: false // 默认为false
}
},
computed: { // subIsShow用来接收父路由isShow传过来的值,但是不能直接操作,所以用val进行接收并操作
val: function () {
return this.subIsShow // 把subIsShow的值给val
}
},
methods: {
changed () {
this.$emit('update:subIsShow', !this.val) // 把val的值更新给subIsShow,这时因为subIsShow和isShow同步,所以父路由的isShow也进行了更新
}
},
- Three: from father to son
Father route
<Input :subText="text"></Input>
data () {
return {
text: '123456'
}
},
Sub-routing
<input v-model="subText" type="text">
props: {
subText: {
type: String,
default: ''
}
},
- Four: Parent child calling methods / properties can also be
sub-routing
methods: {
test () { // 父组件调用子组件的方法
alert('我是子组件的方法')
}
}
Father route
<button @click="testFn">我是父组件的按钮</button>
<List ref="list" ></List> // 子组件 利用ref获取节点
methods: {
testFn () {
this.$refs.list.test() // 利用ref调用子组件中的方法
}
}