Skip to content

Commit

Permalink
初识vue3中的setup
Browse files Browse the repository at this point in the history
  • Loading branch information
Panyue-genkiyo committed Oct 12, 2021
1 parent e05eef6 commit f3b9e23
Show file tree
Hide file tree
Showing 2 changed files with 101 additions and 0 deletions.
81 changes: 81 additions & 0 deletions 02_src_初识setup/App.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
<template>
<!--vue3的组件模版结构可以没有根标签-->
<h1>我是app组件</h1>
<h1>我叫{{ name }}, {{ age }}岁</h1>
<button @click="sayHello">hello!!</button>
<h3>msg: {{ vue2 }}</h3>
<p>数据冲突该怎么办?{{ a }}</p>
<button @click="test1">测试一下在vue2中去读取vue3的配置</button>
<button @click="test2">测试一下在vue3的setup中去读取vue2的配置</button>
</template>

<script>
// import { h } from 'vue';
export default {
name: 'App',
//此处只是测试setup,暂时先不考虑响应式的问题
//测试使用vue2的内容
data(){
return {
vue2: 'still can use vue2 in vue3 code',
a:1
}
},
methods:{
//vue2配置方法的方式
test1(){
console.log(this.vue2);
console.log(this.name);
console.log(this.sayHello);
this.sayHello();
}
},
setup(){
//表演的舞台
//准备数据 data
let name = 'py';
let age = 21;
let a = 300;
//方法 methods
function sayHello(){
alert(`My name is ${name}, ${age} ${age === 1 ? 'year' : 'years'} old`);
}
//在vue3的配置里去读取vue2的属性
function test2(){
console.log(name);
console.log(age);
console.log(sayHello);
console.log(this.vue2);
console.log(this.test1);
}
//返回一个对象
return {
name,
age,
sayHello,
test2,
a
}
//返回一个渲染函数
//这是直接将你在这里渲染的东西替换到template中
// return () => h('h1', 'hello');
}
}
</script>

<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
20 changes: 20 additions & 0 deletions 02_src_初识setup/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
//引入不再是Vue构造函数了,引入的是一个名为createApp的工厂函数
//注意在这里无法像vue2那样去书写了,(这里并不兼容)
import { createApp } from 'vue'
import App from './App.vue'

//创建应用实例对象---app类似于vue2中vm,但app比vm更轻
const app = createApp(App);
// console.log(app);
//挂载
app.mount('#app');

// setTimeout(() => {
// app.unmount("#app");
// },2000)

// //vue2写法
// const vm = new Vue({
// render: h=> h(App)
// });
// vm.$mount('#app')

0 comments on commit f3b9e23

Please sign in to comment.