Vue组件传值-父传子
重点: 父组件向子组件使用props属性进行传值
<!-- 父组件 -->
<div class="app">
<!-- 直接子组件上进行传值 -->
<!-- step="2"step前面不加:表示传递的是字符串,此时的2为字符串-->
<counter step="2" t="此时的2为字符串"> </counter>
<br />
<!-- :step="2"step前面加:表示传递的是js表达式,此时的2为数字-->
<counter :step="2" t="此时的2为数字"> </counter>
<br />
<!-- 每个子组件之间互不影响 -->
<counter :step="3" t="此时的2为数字"> </counter>
</div>
<script src="../lib/vue.js"></script>
<script>
// 定义一个子组件 counter
const counter = {
data() {
return { count: 1 };
},
template: `
<button @click="count+=step" :title="t">父组件传递的值为:{{step}},计算的值为: {{count}}</button> `,
// 在子组件内使用props属性接受父组件传递的值,有以下两种写法:
// 写法一. 不验证的写法
// props: ["step", "t"]
// 写法二. 可以使用对象的方法定义props实现属性值的验证
props: {
step: {
type: Number, // 表示改参数的数据类型,若数据类型不对会报错
required: true // true 表示必填项,false:表示为非必填项
},
title: {
type: String,
required: true
},
t: {
type: String,
required: true
}
}
};
// 该为父组件
let vm = new Vue({
el: ".app",
components: {
counter
}
});
</script>