前言
根据某站的vue教学视频,看万卷教程不如敲万行代码,根据教学进度整理对应代码,更快的熟悉这门语言
流程
响应式:简单来说就是浏览器页面触发条件(常见点击按钮)后页面数据动态改变。
按以前的代码
html
//data
const name = 'kane'
//methods
//触发下面方法,页面数据是不会改变的
function changeName() {
name = '小伙子'
}
按上面function的方法,数据只在后台这边修改了,页面的响应是不会变,也就是的name值不会变化。要达到页面也同步变化要使用ref或者 reactive
ref和 reactive区别
ref是基本数据类型的响应式,reactive是应用类型的响应式
响应式修改实现
ref响应式
Person.vue
html
<template>
<div class="person">
<h2>姓名:{{ name }}</h2>
<h2>年龄:{{ age }}</h2>
<button @click="changeName">改名</button>
<button @click="changeAge">改年龄</button>
<button @click="showTel">1查看联系方式</button>
</div>
</template>
<script lang="ts" setup name="PersonA">
import { ref } from 'vue'
//data 原来是写在data中的,此时的name、age、tel都不是响应式的数据,加ref变成响应式
const name = ref('kane')
const age = ref(18)
const tel = '1223355446'
//methods
function changeName() {
name.value = '嘿嘿' //加上ref后,这个name就相当于变成了一个实例,我们改的就是这个实例对象的value,所以是修改name.value
console.log(name.value)
}
function changeAge() {
age.value += 1
console.log(age.value)
}
function showTel() {
alert('kane: ' + tel)
}
</script>
<style>
.app {
background-color: red;
box-shadow: 0 0 10px;
border-radius: 10px;
padding: 20px;
}
</style>
reactive响应式
Car.vue
html
<template>
<div class="car">
<h2>汽车信息:一辆{{ car.brand }}车,价值{{ car.price }}万</h2>
<button @click="changePrice">修改汽车的价格</button>
<br />
<h2>游戏列表:</h2>
<ul>
<li v-for="g in games" :key="g.id">{{ g.name }}</li>
</ul>
<button @click="changeFirstGame">修改第一个游戏的名字</button>
</div>
</template>
<script lang="ts" setup name="Car">
import { reactive } from 'vue'
//data
const car = ({ brand: '奔驰', price: 100 })
const games = reactive([
{ id: 'aysdytfsatr01', name: '王者荣耀' },
{ id: 'aysdytfsatr02', name: '原神' },
{ id: 'aysdytfsatr03', name: '三国志' },
])
//methods
function changePrice() {
car.price += 10
}
function changeFirstGame() {
games[0].name = '泡泡堂'
}
</script>
<style scoped>
.person {
background-color: skyblue;
box-shadow: 0 0 10px;
border-radius: 10px;
padding: 20px;
}
button {
margin: 0 5px;
}
li {
font-size: 20px;
}
</style>
Persion.vue和Car.vue注册到App.vue
App.vue
html
<template>
<div class="app">
<h1>hello world</h1>
<Person></Person>
<br />
<br />
<Car></Car>
</div>
</template>
<script lang="ts">
import Person from './components/Person.vue'
import Car from './components/Car.vue'
export default {
name: 'App', //组件名
components: { Person, Car }, //注册组件名
}
</script>
<style>
.app {
background-color: #ddd;
box-shadow: 0 0 10px;
border-radius: 10px;
padding: 20px;
}
</style>
启动
html
npm run dev
效果
点击安你要测试,页面是否响应变化
