setup 使用 props
在 setup 中使用 props
子组件
通过 toRefs 解构出来
要是相对 props 的值 2 次封装,必须用 value
<template>
<div>
{{name}}
{{message}}
</div>
</template>
<script>
import { toRefs } from 'vue'
export default {
props: { name: String },
setup (props) {
const { name } = toRefs(props)
let message = name.value + "今天天气不错"
return {
message
}
}
}
</script>
<style lang="less" scoped>
</style>
父组件
<template>
<div>
<span>{{count}}</span>
<span>{{double}}</span>
<div @click="changecount">点击增加</div>
<span> x:{{x}} y:{{y}}</span>
<H1Component :name="data2"></H1Component>
</div>
</template>
<script>
import { ref, computed, reactive, toRefs, onMounted, watch } from 'vue' //ref接收一个参数 返回一个响应式对象 //computed是一个函数接收一个参数是函数
import useMouseDownHooks from '../hooks/useMousedown'
import H1Component from './H1.vue'
export default {
components: {
H1Component,
},
setup() {
onMounted(() => {
console.log('挂在了')
})
const data = reactive({
count: 0,
double: computed(() => {
return data.count * 2
}),
changecount: () => {
data.count++
},
})
let data2 = ref('哈哈')
watch(data2, (newval, oldval) => {
console.log(data2)
console.log(newval)
console.log(oldval)
})
let { x, y } = useMouseDownHooks() //开始赋值
watch(x, (newval, oldval) => {
// console.log(newval)
// console.log(oldval)
console.log(x.value)
console.log(x)
})
const result = toRefs(data)
return {
...result,
x,
y,
data2,
}
},
}
</script>
<style lang="less" scoped></style>