子组件
<template>
<div v-if="visible">
<p>{{header}}</p>
我是子组件:{{num}}
</div>
</template>
<script>
export default {
components: {
},
props: {
header:{
type:String,
required:false,
default:''
}
},
data(){
return {
num:'',
visible:false
}
},
mounted(){
this.$parent.message = new Date()
},
methods:{
add(){
this.visible = true
}
}
};
</script>
父组件
<template>
<div id="app">
<example ref="example" :header="header"></example>
子组件给父组件传值:{{message}}
<a-button @click="open">子组件</a-button>
</div>
</template>
<script>
import example from '@/components/example'
export default {
components:{
example
},
mounted(){
this.$refs.example.num = 222
},
data() {
return {
header:'我是父组件给子组件传的值',
message:''
}
},
created(){
console.log('数据',this.$data,this.data)
},
methods: {
open(){
this.$refs.example.add()
}
}
}
</script>
<style scoped>
</style>
vm.$data
Vue 实例观察的数据对象。Vue 实例代理了对其 data 对象 property 的访问
created(){
console.log('数据',this.$data,this.data) //this指向当前实例对象
},
vm.$props
当前组件接收到的 props 对象。Vue 实例代理了对其 props 对象 property 的访问。
//在子组件中
mounted(){
console.log('数据',this.$props)
},
vm.$el
Vue 实例使用的根 DOM 元素
methods: {
open(){
this.$refs.example.add()
console.log('$el',this.$refs.example.$el.innerText)
}
}
vm.$options
用于当前 Vue 实例的初始化选项。
created(){
console.log('数据',this.$data,this.data)
console.log('$options',this.$options.data)
},
<template>
<div id="app">
<example ref="example" :header="header"></example>
子组件给父组件传值:{{message}}
<a-button @click="open">子组件</a-button>
<div>{{tempArr}}</div>
</div>
</template>
<script>
import example from '@/components/example'
export default {
components:{
example
},
mounted(){
this.$refs.example.num = 222
},
data() {
return {
header:'我是父组件给子组件传的值',
message:'',
tempArr:[
{
name:'tom',
age:11
},{
name:'terry',
age:12
},{
name:'larry',
age:13
}
],
list:[]
}
},
created(){
},
methods: {
open(){
this.$refs.example.add()
console.log('$el',this.$refs.example.$el.innerText)
this.list = this.$options.data() //获取data中定义的初始化数据
console.log('this.list',this.list)
this.tempArr.push({ name:'tom',age:11})
console.log('this.list',this.list)
}
}
}
</script>
<style scoped>
</style>
与深拷贝有相似功能,改变某个数据时,可以确保获取初始化的数据
vm.$parent
父实例,如果当前实例有的话
vm.$children
当前实例的直接子组件