vue-cli易错整理
refs的用法
$refs 拿到的是子组件的VM对象; getElementById 只能拿到子组件标签;
<h2 id="BlogItem" ref="BlogItem">小白</h2>
-----------------------------------------------
console.log(document.getElementById("BlogItem"));
console.log(this.$refs.BlogItem);
子组件套用父组件的数据(props的用法)
//父组件.vue
<BlogItem v-for="itme in itmes" :key="itme.id" :myitme="itme" />
------------------------------------------------------------------
data(){
return{
itmes:[
{id:1,title:'这是一个标题一',message:'这是副标题描述一',author:'张三',views:2000,msg:3,time:'2020-09-08'}
]
}
}
//子组件
<div>
<h2>{{myitme.title}}</h2>
<p>{{myitme.message}}</p>
<span>{{myitme.author}}</span>
<span>{{myitme.views}}</span>
<span>{{myitme.msg}}</span>
<span>{{myitme.time}}</span>
</div>
-----------------------------------------
props:{
myitme:{//完整接收
type: Object
}
}
//或者如下接收(一般接收,这样可以拦截信息进行验证)
-----------------------------------------------
props:{
title:{//一般接受
type:String,
required:true//必须传递参数
},
message:String,
author:String,
views:{
type:Number,
default:0//默认值为0
},
msg:Number,
time:String
}
局部样式
问题:不同组件之间css选择器名一样造成样式冲突问题?? ** 解决方式:
混入/混合
问题:解决父组件和各子组件之间有过多重复代码
- src下建一个js文件,用于存放公共数据(我这里是mixin.js文件)
//这里也可以2个合在一起写;该文件中可以抽出data,method,watch、mounted等
export const info = {
methods:{
showMsg(){
alert("小白你好~");
}
}
}
export const userMsg ={
data(){
return {
message:'混入和混合'
}
}
}
- 组件中导入文件(注意:mixins是个属性,名字不可随意)
<script>
import {info,userMsg} from '../mixin.js'
export default {
name:'BiliBili',
mixins:[info,userMsg]
}
</script>
**组件之间值传递(有点绕,要认真)
描述:2个子组件(School.vue和Student.vue)和一个父组件App.vue。 School组件中可以手动输入学生数据,存在父组件的data中,Student显示父组件中的学生数据 注意代码中的addStudent的关系 //App.vue
<template>
<div id="app">
<h1 class="bgcolor">{{msg}}</h1>
<School :addStudent="addStudent2"/>
<hr>
<Student v-for="stu in students" :key="stu.id" :stu1="stu"/>
</div>
</template>
<script>
import School from './components/School.vue'
import Student from './components/Student.vue'
export default {
name: 'App',
components: {
School,
Student
},
data(){
return{
msg:'组件间值传递',
students:[
{id:'001',uname:'张三',age:10,sex:'女'},
{id:'002',uname:'李铁锤',age:18,sex:'女'},
{id:'003',uname:'王二蛋',age:10,sex:'男'},
{id:'004',uname:'淑芬',age:10,sex:'女'}
]
}
},
methods:{
addStudent2(stu){
this.students.unshift(stu);
}
}
}
</script>
//Student.vue
<template>
<div>
<h1>{{stu1.uname}} {{stu1.age}} {{stu1.sex}}</h1>
</div>
</template>
<script>
export default {
name:'Studnet',
props:{
stu1:{
type: Object
}
}
}
</script>
//School.vue
<template>
<div>
<h1 class="bgcolor">希望小学</h1>
姓名:<input type="text" v-model="name"><br>
年龄:<input type="text" v-model="age"><br>
性别:<input type="text" v-model="sex"><br>
<button @click="addStu()">添加学生</button>
</div>
</template>
<script>
import {nanoid} from 'nanoid'
export default {
name:'School',
data(){
return{
name:'',
age:'',
sex:''
}
},
props:['addStudent'],
methods:{
addStu(){
const student = {id:nanoid(),uname:this.name,age:this.age,sex:this.sex}
this.addStudent(student);
}
}
}
</script>
|