Vue_组件参数传递
本讲主要讲的就是组件中的prop
实例:
1.按钮显示/隐藏div内容
2.传入普通字符串
3.组件中遍历数组与对象
<body>
<div id="app">
<display></display><br>
<school title="标题" content="内容"></school><br>
<school title="清华" content="985"></school><br>
<!-- <school title='{{schoolName}}'></school> 直接赋值不行,需要绑定属性 -->
<school :title='schoolName'></school><br>
<name v-for="(arr,index) in arrs" :arr="arr" :index="index=index+1"></name>
</div>
</body>
<script>
//定义一个全局组件,命名为display,data中默认显示,methods中change方法控制显示和隐藏,最后通过@click点击事件来触发
Vue.component('display', { //驼峰方式命名要在脚手架中使用
data: function () {
return {
result: true
}
},
methods: {
change: function () {
// console.log(this.result);
this.result = !this.result;
}
},
template: '<div><button @click="change">显示/隐藏</button><div v-if="result">我是显示的内容</div></div>'
})
//创建一个对象
let school = {
data: function () {
//返回需要传递的参数值
return {
title: '标题',
content: '内容',
}
},
props: ['title', 'content'], //数组,对外暴露一个变量名
template: '<div style="color:red">{{title}}{{content}}</div>'
}
let name = {
props:['arr','index'], 数组,对外暴露一个变量名,传入的类型可以有多种,而且可以传入多个值
template:'<div>{{index}} 姓名:{{arr.name}} 年龄:{{arr.age}}</div>'
}
new Vue({
el: "#app",
data: {
result: true,
schoolName:'清华大学',
arrs:[ //vue怎么遍历数组,对象:v-for
{name:'LiHua', age:'18'},
{name:'Michael', age:'19'},
{name:'Jack', age:'21'},
{name:'Mary', age:'20'},
]
},
components: {
school, // school:school 的简写 //School 驼峰方式不行,要在脚手架中使用
name,
}
})
</script>
效果:👇👇👇👇👇👇👇