ref 的使用:
- 标签中直接编写 ref=“xxx”
- 通过this.$refs.xxx获取
- 若给HTML内置标签打ref,则获取的是真实的DOM节点
- 若给组件标签内打ref,则获取的是组件实例化对象
ref的用法:
- 给组件标签添加指定ref:< Demo ref=“xxx”/> 获取的是组件实例化对象
- 给HTML标签指定ref:< input ref=“xxx”/> 获取的是真实DOM节点
- 通过this.$refs.xxx获取
<template>
<div id="app">
<button @click="btn">点击</button>
<input type="text" ref="keyWord">
<HelloWorld ref="zujian"></HelloWorld>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
export default {
name: 'App',
components: {
HelloWorld
},
methods: {
btn() {
console.log(this.$refs.keyWord.value) // 获取节点的值
console.log(this.$refs.zujian) // 获取的是实例化组件对象
}
}
}
</script>
props 父传子
props的用法:
- 传递props:< Demo :a=“xxx”/>
- Demo组件中声明接收:
第一种方式(只声明)
props:[‘deName’]
第二种方式(限制类型)
props:{deName: String}
第三种方式(限制类型、属性、指定默认值)
props:{
deName:{type:String,required:true,defaulte:“不写就显示默认”}
}
这是父组件App.vue
<template>
<div id="app">
<HelloWorld ref="zujian" :deName="demo"></HelloWorld>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
export default {
name: 'App',
data() {
return {
demo: {
a: 1,
b: 2,
c: 3
}
}
},
components: {
HelloWorld
}
}
</script>
这是子组件HelloWorld.vue
<template>
<div class="hello">
<p>姓名{{ name }}</p>
<p>年龄{{ age }}</p>
<p>父组件传过来的值:{{ deName }}</p>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data() {
console.log(this, "我是组件的this")
return {
name: "张三",
age: 18
}
},
// 完整写法:限制了类型、控制的必要、指定默认值
props: {
deName: {
type: String,
require: true,
default: "默认default"
}
}
// 次要写法:限制类型
/*props: {deName: Object} */
// 精简写法
/*props: ["deName"]*/
}
</script>
watch监视属性
如果todos里的value发生变化的话,log(value)是不会打印东西的,默认的是浅度的监视
watch: {
todos(value) {
console.log(value)
}
}
深层监视,这样可以打印的出来
watch: {
todos: {
deep: true, // 开启深度监视
handler(value) {
console.log(value)
}
}
}
$emit 子传父
子组件给父组件传递数据用this.$emit(给谁发送,发送出去的数据)发射出去数据
子组件
<template>
<div>
<button @click="btn">点击我给父组件发送数据</button>
</div>
</template>
<script>
export default {
name: "Home",
data() {
return {
n: "我是子组件的内容"
}
},
methods: {
btn() {
this.$emit('pr', this.n)
}
}
}
</script>
父组件
<template>
<div id="app">
<Home @pr="Apppr" />
子组件传过来的数据:{{ a }}
<!--如果子组件没有传过来数据,就用自己的数据-->
</div>
</template>
<script>
import Home from "@/components/Home"
export default {
name: 'App',
components: {
Home
},
data() {
return {
a: "dasd"
}
},
methods: {
Apppr(value) {
this.a = value
}
}
}
</script>