vue父子组件间传值
子组件
<template>
<div class="confirm_button">
<el-button type="primary" @click="getButtonClick">{ { text || 确定}}</el-button>
</div>
</template>
<script>
export default {
name: "confirm-button",
props:["text"],
watch: { },
data: function(){
return{
msg: this.text=="提交"?"提交成功":true
}
},
//方法集
methods:{
getButtonClick(){
this.$emit("message",this.msg)
}
},
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
父组件
<template>
<div class="hello">
{ { msg}}
<confirm text="提交" @message="getMessage"></confirm>
<ul id="treeDemo" class="ztree"></ul>
<!-- <div id="jq" @click="initZtreeMethod">hello world</div> -->
</div>
</template>
<script>
import $ from '../assets/jquery-vendor.js'
import 'ztree/js/jquery.ztree.core'
import 'ztree/js/jquery.ztree.excheck'
import 'ztree/css/zTreeStyle/zTreeStyle.css'
import confirm from './sub/Confirm'
export default {
name: "hello",
components:{
confirm
},
data: function(){
return{
zNodes:[
{ id:0,pId:null,name:"root"},
{ id:1,pId:0,name:"child"}
],
setting:{
data:{
keep:{
leaf: false,
parent: false
},
simpleData:{
enable: true,
idKey: 'id',
pIdKey: 'pId',
rootPId: null
},
}
},
msg: "Welcome to my first app"
}
},
//方法集
methods:{
initZtreeMethod(){
$.fn.zTree.init($("#treeDemo"), this.setting, this.zNodes);
},
getMessage(val){
this.$message(val+"");
}
},
mounted(){
this.initZtreeMethod();
},
created(){
},
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
效果展示
讲解
父组件向子组件传值使用props
//一些props使用的语法
//静态
props: [“for-child-msg”]//动态props
props: {
// 基础类型检测, null意味着任何类型都行
propA: Number,
// 多种类型
propB: [String, Number],
// 必传且是String
propC: {
type: String,
required: true
},
// 数字有默认值
propD: {
type: Number,
default: 101
},
// 数组、默认值是一个工厂函数返回对象
propE: {
type: Object,
default: function() {console.log("propE default invoked.");
return { message: "I am from propE." };
}
},
// 自定义验证函数
propF: {
isValid: function(value) {return value > 100;
}
}
}
上面是props语法,子组件需要使用props来接受父组件的传值,父组件上需要定义一个和props里面相同的属性,然后给属性赋值。
- 子组件向父组件传值需要使用this.$emit(“方法名”,“传递的值”),点击的时候会触发getButtonClick方法,然后触发message方法,在父组件也就是getMessage方法,其中的方法参数就是子组件向父组件传递的值.
还没有评论,来说两句吧...