2018-09-21
关于Vue.js里的子传父:其原理是用事件传
(用emit('自定义事件',参数)。
举例如下:
子组件向父组件传值==>
①
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id='app'>
<father></father>
</div>
<script src='js/vue.js'></script>
<script>
Vue.component('father', {
template: `
<div>
<h1>{{mess}}</h1>
<son @send='rcvMsg'></son>
</div>
`
, data: function () {
return {
mess: ''
}
}
, methods: {
rcvMsg: function (txt) {
this.mess = txt;
}
}
})
Vue.component('son', {
template: `
<button @click='sendToFather'>我是子组件,我要向父组件传值</button>
`
, data: function () {
return {
msg: '子组件向父组件传值'
}
}
, methods: {
sendToFather: function () {
this.$emit('send', this.msg)
}
}
})
new Vue({
el: "#app"
})
</script>
</body>
</html>
效果图:
son01.png son02.png②
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id='app'>
<my-father></my-father>
</div>
<script src='js/vue.js'></script>
<script>
Vue.component('my-father', {
template: `
<div>
<h1>{{mess}}</h1>
<my-child @send='revMsg'></my-child>
</div>
`
, data: function () {
return {
mess: ''
}
}
, methods: {
revMsg: function (txt) {
this.mess = txt
}
}
})
Vue.component('my-child', {
template: `
<button @click='sendFather'>给父组件</button>
`
, data: function () {
return {
msg: '给你咯~~~'
}
}
, methods: {
sendFather: function () {
// this.$emit('自定义事件',参数)
this.$emit('send', this.msg)
}
}
})
new Vue({
el: "#app"
})
</script>
</body>
</html>
效果图: son04.png
add02.png son03.png③
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id='app'>
<my-father></my-father>
</div>
<script src='js/vue.js'></script>
<script>
Vue.component('my-father', {
template: `
<div>
<input type='text' v-model='fruit'> <button @click='add'>添加</button>
<my-child v-bind:fruList='list'></my-child>
</div>
`
, data: function () {
return {
list: ['apple', 'pear', 'orange']
, fruit: ''
}
}
, methods: {
add: function () {
this.list.push(this.fruit)
}
}
})
Vue.component('my-child', {
props: ['fruList']
, template: `
<ul>
<li v-for="(value,index) in fruList">
{{value}}
<button @click='delt(index)'>删除</button>
</li>
</ul>
`
, methods: {
delt: function (ind) {
this.fruList.splice(ind, 1)
}
}
})
new Vue({
el: '#app'
})
</script>
</body>
</html>
网友评论