Vue3
Vue.js 是一个流行的前端 JavaScript 框架,用于构建用户界面和单页面应用程序(SPA)。Vue 3 是 Vue.js 的最新版本
安装 Vue
项目
npm init vue@latest
npm create vue@latest //在其他后端里安装
安装 NPM
npm i
安装 Axios
(如有需要)
npm i axios
启动
npm run dev
Vue 基础
在.eslintrc.cjs
文件里添加, 可随意命名文件名称 (如有需要,可以忽略)
rules: {
'vue/multi-word-component-names': 0, // 不再强制邀请组件命名
}
区别:
reactive
适用于包装对象,并且适用于对象的所有属性。ref
适用于包装单个值,并且需要使用.value
来访问和更新值。
Reactive 用法
import { reactive } from 'vue'
const state = reactive({
count: 0
})
// 访问属性
console.log(state.count) // 输出: 0
// 更新属性
state.count++
console.log(state.count) // 输出: 1
Ref 用法
import { ref } from 'vue'
const count = ref(0)
// 访问属性
console.log(count.value) // 输出: 0
// 更新属性
count.value++
console.log(count.value) // 输出: 1
Computed 用法
自动再次计算,然后输出
import { computed } from 'vue'
const list = ref([1,2,3,4,5,6,7,8])
const computedList = conputed(() => {
return list.value.filter(item => item > 2);
})
setTimeout(() => {
list.value.push(9,10);
})
Watch 函数
import { ref, watch } from 'vue'
const count = ref(0)
watch(count, (newValue, oldValue) => {
console.log('count发生了变化,老值为${oldValue}, 新值为${newValue}')
})
Watch 函数 多听变化
import { ref, watch } from 'vue'
const count = ref(0)
const name = ref('cp')
watch(
[count, name],
([newCount, newName], [oldCount, oldName]) => {
console.log('count或者name发生了变化,[newCount, newName], [oldCount, oldName]')
}
)