1.报错
(1)Uncaught SyntaxError : 语法错误
(2)Cannot read property 'focus' of undefined : focus前面的成员是未定义的
例子:this.$refs.refInput.focus() refInput就是未定义的
2.安装包的方法
(1)yarn add xxx -S 简写 --save
安装的包会放到dependecies对象里面 开发和上线都要用到
(2)yarn add xxx -D 简写 --save-dev
安装的包会放到devDependecies对象里面 开发阶段要用到
tips:是否需要带-S还是-D,请查阅官方文档 npm
3.vue.config.js文件
module.exports = {
modes: 'development', // 运行模式,可选值 development 和 production
// __dirname:该文件的根路径,拼接src/index1.js路径
entry: path.join(__dirname, './src/index1.js'), // 打包入口文件
output: {
path: path.join(__dirname, 'dist'), // 存放到目录
name: 'bundle.js' // 生成的文件名
}
}
4.watch侦听器
(1)函数格式的侦听器:
缺点一:进入页面时无法自动触发!!
缺点二:如果侦听的是一个对象,对象属性发生改变时,不会触发侦听器!!
<input v-model="username" />
watch: {
username(newVal, oldVal) {
console.log('数据发生了变化!')
}
}
(2)对象格式的侦听器:
优点一:进入页面时可以自动刷新
优点二:可以侦听对象里面每个属性的变化
watch: {
username: {
handler(newVal, oldVal) {
console.log('数据发生了变化')
},
immediate: true, // 作用:进入页面时立即执行一次
deep:true // 开启深度监听,对象中任何一个属性发生变化都会触发侦听器
}
}
5.computed计算属性
特点:
(1)定义时,要被定义为方法
(2)使用计算属性时,当成普通属性使用即可
优点:
(1)实现了代码复用
(2)只要计算属性中的数据源发生了变化,计算属性就会自动重新求值
<input v-model.number="r" />
<input v-model.number="g" />
<input v-model.number="b" />
// :style代表动态绑定一个对象,他的值是一个{ }样式对象
<div :style="{ backgroundColor: `rgb(${r},${g},${b})` }"
data() {
r: 0,
g: 0,
b:0
}
methods: {
show() {
console.log(`rgb(${r},${g},$[b})`)
}
}
// 以上模板字符串的方法在多个地方代码重复:rgb(${r},${g},${b})
//计算属性要定义成方法格式
computed: {
rgb() {
// 在该方法中要返回一个生成好的 rgb(x,x,x) 的字符串
return `rgb(${this.r},${this.g},${this.b})
}
}
// 这时,rgb与r,g,b同级
// rgb这个计算属性可以用于模板字符串
<div :style="{ backgroundColor: rgb }"
methods: {
show() {
console.log(this.rgb )
}
}
6.async/await
如果调用的某个方法的返回值是Promise实例,则前面可以添加await
7.this.$nextTick的应用场景
this.$nextTick可以保证其内部的方法可以操作到最新的DOM元素
<input v-if="inputVisible" ref="iptRef" @blur="showButton" />
showButton() {
this.inputVisible = true
this.$refs.iptRef.focus() // 此时报错:Cannot read property 'focus' of undefined
// 因为此时input虽然已将拿到数据this.inputVisible = true,
// 但页面渲染还需要时间,使用$refs获取时,input框还没渲染出来
}
// 解决方法:当页面重新渲染完毕后,再获取iptRef这个DOM ==> this.$nextTick(cb)
showButton() {
this.inputVisible = true
this.$nextTick(() => {
this.$refs.iptRef.focus()
})
}
8.some()
在数组里面找元素,用some合适
const arr = ['小红', '倪大红', '苏大强', '宝']
// forEach一旦开始,无法在中间被停止
arr.forEach((item, index) => {
console.log(item) // 该语句被打印4次,表示return不生效
if (item === '苏大强') {
return
}
})
arr.some((item, index) => {
console.log(item)
if (item === '苏大强') {
// 找到对应项后,用 return true 固定语法 来终止some循环
return true
}
})