一、vue基础使用
将App.vue都删掉按照以下结构编写代码这就是起步模板
<template>
<div>{{msg}}</div>
</template>
<script>
// defineComponent函数,目的是定义一个组件,内部可以传入一个配置对象
import { defineComponent } from 'vue'
// 暴露出去一个定义好的组件
export default defineComponent({
setup() {
const msg = '天天真帅'
return {
msg
}
},
})
</script>
<style scoped>
</style>
然后在终端输入npm run dev 进入界面就会是这样的我们自己编写的第一个vue就跑起来了。
二、setup和ref基本使用
我们来写一个计数器实现点一下就+1的功能
以下是完整代码介绍都在注释中:
<template>
<!-- 由于我的插件没有跟新所以我用div把他们包了起来这样不会爆红,即使爆红也不影响代码正常运行 -->
<div>
<!-- 想使用steup返回的数据需要用{{}}把变量名包起来 -->
<div>{{msg}}</div>
<h1>{{count}}</h1>
<!-- @click点击方法 ="add" 指定调用哪个方法 方法需要被steup返回 -->
<button @click="add">点我+1</button>
</div>
</template>
<script>
// defineComponent函数,目的是定义一个组件,内部可以传入一个配置对象
import { defineComponent, ref } from 'vue'
// 暴露出去一个定义好的组件
export default defineComponent({
setup() {
// 阐述一个事实很重要,这句话没了会报错(狗头)
const msg = '天天真帅'
// ref作用是定义一个响应式的数据,返回的是Ref对象。
const count = ref(0)
// 定义一个方法实现button点击count+1的功能
function add(){
// 由于ref返回的是对象所以不可以直接 count ++ 对象不可以++ 需要使用对象中的方法value取出其中的值进行++
count.value ++
}
// 返回模板中需要的数据
return {
msg,
count,
add
}
},
})
</script>
<style scoped>
</style>
三、reactive的基本使用
reactive可以定义多个数据的响应式
需求:展示个人信息,在点击按钮后类似于过一年的效果,年龄增加,网站功能增加。
<template>
<div>
<h3>名字:{{user.name}}</h3>
<h3>年龄:{{user.age}}</h3>
<h3>网站名字:{{user.web.name}}</h3>
<h3>网站年龄:{{user.web.age}}</h3>
<h3>网站地址:{{user.web.path}}</h3>
<h3>网站功能:{{user.web.feature}}</h3>
<button @click="update">一年后</button>
</div>
</template>
<script>
import { defineComponent, reactive} from 'vue'
export default defineComponent({
setup() {
// reactive给多个一个复杂的数据定义深度响应式
const user = reactive({
name:'小天',
age:20,
web:{
name:'天天搜题',
age:1,
path:'http://tiantiansouti.com/',
feature:['搜题','登录','留言']
}
})
// function update(){}
const update = () => {
// 过一年后修改小天的年龄并且修改网站的年龄
user.age += 1
user.web.age += 1
// 并且一年后还增加了注册功能(有个小bug暂时就不说了如何避免大家可以自行解决)
user.web.feature.push('注册')
}
return {
user,
update
}
},
})
</script>
<style scoped>
</style>
页面结果