vue3 setup语法糖
记vue3 setup script语法糖使用的一些问题
vue3新语法糖——setup script
1.原来
<script>
import { ref } from 'vue'
import HelloWorld from './components/HelloWorld.vue'
export default {
components: {
HelloWorld
},
setup(){
const data = ref(1);
const add=()=>{
data.value++;
}
return{
data,
add
}
}
}
</script>
2.现在
- 属性和方法无需返回,不用在setup return了
- 子组件不用在components里面注册了
<script setup>
import { ref } from "vue";
import HelloWorld from "./components/HelloWorld.vue";
const data = ref(1);
const add = () => {
data.value++;
};
</script>
组件传值
1.原来
<script>
export default {
props: {
msg: String
},
}
</script>
2.现在
- 使用defineProps 接收props
<script setup>
import { defineProps } from 'vue'
const props = defineProps({
msg: String
})
</script>
父调用子组件
- 父组件
<HelloWorld @child-click="add" ref="childRef" />
<script setup>
import { ref } from "vue";
import HelloWorld from "./components/HelloWorld.vue";
const childRef = ref(null);
const tapChild = () => {
childRef.value.childFunction()
};
</script>
1.原来
子:<script >
export default {
setup() {
const childFunction = () => {
console.log("我是child方法");
};
return {
childFunction
};
},
};
</script>
2.现在
- 当使用
<script setup>时,可以把<template>看成是setup作用域内的一个function,这样setup就相当于一个闭包,除了内部的<template>谁都访问不到其作用域内的数据。 - 所以,传统setup写法里我们可以在父组件中通过子组件的ref实例来访问子组件的数据和方法(childRef.value.someFn()),到了
<script setup>里这一套就行不通了,需要显示地向外暴露你想暴露的内容。
<script setup>
import { defineExpose } from 'vue'
const childFunction = () => {
console.log("我是child方法");
};
defineExpose({
childFunction
})
</script>
子调用父方法emit
父:<Father @child-click="add" />
1.原来
子:<button @click="handleClick">add father</button>
<script>
export default {
emits: [
'child-click'
],
props: {
msg: String
},
setup(props,context){
const handleClick = () => {
context.emit('child-click', context)
}
return{
handleClick
}
}
}
</script>
2.现在
<script setup>
// 其中defineProps用来接收父组件传来的值props。defineEmits用来声明触发的事件表。
// attrs是父组件传递给子组件的属性中除了props、class以及style外的属性:
import { useAttrs, defineEmits, defineProps } from "vue";
const attrs = useAttrs();
const props = defineProps({
msg: String,
});
const emit = defineEmits(["child-click"]);
const handleClick = () => {
console.log(props);
console.log(attrs);
emit("child-click", "向父传递的值");
};
</script>
留言讨论