Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit a9615fe

Browse files
committedOct 13, 2021
vue3中setup的注意点
1 parent 31ac7ac commit a9615fe

File tree

3 files changed

+104
-0
lines changed

3 files changed

+104
-0
lines changed
 
+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
<template>
2+
<!--vue3的组件模版结构可以没有根标签-->
3+
<Demo @hello="showHelloMsg" msg="hello" school="wust">
4+
<template v-slot:qwe>
5+
没事
6+
</template>
7+
<template v-slot:asd>
8+
love you
9+
</template>
10+
</Demo>
11+
</template>
12+
13+
<script>
14+
import Demo from "./components/Demo";
15+
export default {
16+
name: 'App',
17+
components: {Demo},
18+
setup(){
19+
return {
20+
showHelloMsg(value){
21+
alert(`你好,${value}`);
22+
}
23+
}
24+
}
25+
}
26+
</script>
27+
28+
<style>
29+
#app {
30+
font-family: Avenir, Helvetica, Arial, sans-serif;
31+
-webkit-font-smoothing: antialiased;
32+
-moz-osx-font-smoothing: grayscale;
33+
text-align: center;
34+
color: #2c3e50;
35+
margin-top: 60px;
36+
}
37+
</style>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
<template>
2+
<!--vue3的组件模版结构可以没有根标签-->
3+
<h1>我是app组件</h1>
4+
<h1>我叫{{ person.name }}, {{ person.age }}岁</h1>
5+
<button @click="test">测试触发一次demo的自定义事件</button>
6+
</template>
7+
8+
<script>
9+
import { reactive } from 'vue';
10+
export default {
11+
name: 'Demo',
12+
beforeCreate() {
13+
console.log('----@bc');
14+
},
15+
props: ['msg', 'school'],
16+
emits:['hello'],
17+
setup(props, context){
18+
// console.log('----setup');
19+
// console.log(this); ///undefined
20+
console.log(props); //props: 外部给组件丢的参数 => 响应式(Proxy实例)
21+
//表演的舞台(setup)
22+
//准备数据 data
23+
//ref实现响应式(基本类型)也是采用Object.definedProperty()来实现的 getter和setter
24+
// let name = ref('py'); //ref引用对象(RefImpl)实例
25+
// let age = ref(21);
26+
//ref实现响应式(对象类型)也是采用Proxy来实现(proxy) 这里如果就算是用ref也是借助了reactive
27+
let person = reactive({
28+
name: 'py',
29+
age: 21,
30+
});
31+
32+
// console.log(context, context.attrs); 相当于vue2中的$attrs
33+
// console.log(context,context.slots); 插槽
34+
35+
//返回一个对象
36+
return {
37+
person,
38+
test(){
39+
context.emit('hello', 666); //触发自定义事件
40+
}
41+
}
42+
}
43+
}
44+
</script>
45+
46+
<style>
47+
</style>
+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
//引入不再是Vue构造函数了,引入的是一个名为createApp的工厂函数
2+
//注意在这里无法像vue2那样去书写了,(这里并不兼容)
3+
import { createApp } from 'vue'
4+
import App from './App.vue'
5+
6+
//创建应用实例对象---app类似于vue2中vm,但app比vm更轻
7+
const app = createApp(App);
8+
// console.log(app);
9+
//挂载
10+
app.mount('#app');
11+
12+
// setTimeout(() => {
13+
// app.unmount("#app");
14+
// },2000)
15+
16+
// //vue2写法
17+
// const vm = new Vue({
18+
// render: h=> h(App)
19+
// });
20+
// vm.$mount('#app')

0 commit comments

Comments
 (0)
Please sign in to comment.