component( ) 自定义组件时经常会用到参数,主要有两种情况:父向子传参、子向父传参。
父子传参:
在父子传参中需要用到的是 component 中的 props 属性,props 是一个数组,包含了父级组件传来的参数。
下面这个例子中,定义了一个 user 组件,用来显示一个名字的 a 标签,当点击时跳转到该名字的页面。用法如下:
<!doctype html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title>prop</title>
</head>
<body>
<div id="app">
<user username="Talon"></user>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script type="text/javascript">
Vue.component('user', {
template: '<a :href="\'/user/\'+username">{{username}}</a>',
props: ['username'],
})
new Vue({
el: '#app'
})
</script>
</body>
</html>
子父传参:
上面实现了父子之间的传参,现在实现以下子父之间的传参。先自定义两个组件 balance 和 show,用来显示余额。在 balance 组件的模板中调用 show 组件,然后将参数在 show 组件中传到 balance 中。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<div id="app">
<balance></balance>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script type="text/javascript">
Vue.component('balance', {
template: `
<div>
<show @show-balance="show_balance"></show>
<div v-if="show">
您的余额:{{money}}
</div>
</div>
`,
data: function () {
return{
show: false,
money: 0,
}
},
methods: {
show_balance: function (data) {
this.show = true;
this.money = data;
}
}
});
Vue.component('show', {
template: '<button @click="onClick">显示余额</button>',
methods: {
onClick:function () {
this.$emit('show-balance', 100);
}
}
});
new Vue({
el: '#app'
})
</script>
</body>
</html>