使用style设置背景
<!-- 在assets里面的文件 在img中是可以正常使用的 -->
<!-- <img src="./assets/1.webp" alt=""> -->
<!-- style="background:url(./assets/1.webp) no-repeat" -->
<!-- 使用style的方式使用backgroud是不能解析里面的路径的 -->
<!-- 解决方式1 把图片放在根目录public下 使用/表示public根目录 -->
<!-- style="background:url(/imgs/1.webp) no-repeat" -->
<!-- 使用require方法把原来不解析的路径 手动解析一遍 -->
<div class="bg" :style="{background:'url('+require('./assets/1.webp')+') no-repeat'}">
组件之间传值:
父组件:
<script>
/* 第一步导入组件 */
// import ChildA from './components/ChildA.vue'
/* @就代表src文件夹 */
import ChildA from '@/components/ChildA.vue'
import ChildB from '@/components/ChildB.vue'
export default {
name: 'App',
/* 第二步注册组件 */
components:{
ChildA,
ChildB
},
/* 爷爷级通过provide把data中的属性给到sunMsg */
/* provide的里面的数据是可以传递给子级使用(包括儿子)
数据是向下传递的 */
/* 传固定的值可以用下面的方式 */
// provide:{
// sunMsg:'爷爷的祖宅'
// },
/* 但是传动态的值需要使用函数的方式 */
provide:function(){
return {
/* 如果yeye是后台返回的动态数据
要使用箭头函数的方式定义
sunMsg是一个函数 在使用的时候需要调用*/
sunMsg:()=>this.yeye,
mm:"我爱你哦宝贝"
}
},
/*父组件使用this.$children必须在mounted子组件加载
完毕的时候时候,不能在created钩子函数的时候执行
因为子组件还没有加载完毕 */
mounted(){
/* 使用this.$children也可以获取子组件的属性
和方法 */
/* this.$children 是一个数组 */
// console.log( this.$children[0] )
console.log(this.$children[0])
this.$children[0].changeStr();
// console.log(this.$children[1].s1)
/* 模拟后台返回的数据 */
setTimeout(()=>{
this.yeye = '我爱你哦 可爱的小孙子'
},500)
},
data:function(){
return {
yeye:'',
msg:"我是父组件App派下来的",
str:'我是父组件没传的属性',
}
},
methods:{
fn:function(){
// this.$children[0].changeStr();
this.$children[1].changes();
},
handler:function(){
this.msg = '子改父'
},
changeStr:function(){
this.str = '123'
}
}
}
</script>
子组件A:
<template>
<div>
<!-- <h1 @click="change">{{msg}}</h1>
<h1>{{$parent.str}}</h1> -->
<h1>{{childStr}}</h1>
</div>
</template>
<script>
export default {
name:"ChildA",
props:['msg'],
created(){
/* 使用this.$parent可以获取父组件没传的属性和方法 */
// console.log( this.$parent.str )
/* 使用this.$parent可以在子组件里面调用父组件的方法 */
this.$parent.changeStr();
},
data:function(){
return {
childStr:'childStr'
}
},
methods:{
change:function(){
this.$emit('handler')
},
changeStr:function(){
this.childStr='parentStr'
}
}
}
</script>
子组件B:
<template>
<div>
<!-- <h1>{{s1}}</h1> -->
<h1 style="color:red">{{sunMsg()}}</h1>
<SunZi />
</div>
</template>
<script>
import SunZi from '@/components/SunZi.vue'
export default {
name:'ChildB',
components:{
SunZi
},
/* 儿子也可以使用他爸爸传过来的sunMsg数据 */
inject:['sunMsg'],
props:['msg'],
data:function(){
return {
s1:'我是ChildB'
}
},
methods:{
changes:function(){
this.s1 = '123'
}
}
}
</script>
孙组件:
<template>
<div>
<hr>
<h1>我是孙子组件</h1>
<h1>{{sunMsg()}}</h1>
<h1>{{mm}}</h1>
</div>
</template>
<script>
export default {
name:"SunZi",
/* 孙子可以使用inject获取爷爷传过来的sunMsg数据 */
inject:['sunMsg','mm']
}
</script>