今天写一个input的上传demo例子玩,主要想实现的效果是父组件图片变化,子组件也跟着变化
写的过程中发现父组件已经更新图片,而子组件无动于衷,想着是无法深度监听,就是watch了一下deep,但是还是不行,连watch都没进去,
经过一段时间的找bug,后来发现没有$set,所以vue无法感知到所以无法更新,真的是纸上得来终觉浅,还是需要多敲,coding
我敲
例子:
父组件
<template>
<div>
<div>
<h1>上传组件</h1>
<input ref="uploadInput"
type="file"
@change="chooseImg">
</div>
<div>
<ImgShow :imgValue="imgValue"
:url="url" />
</div>
<div class="show">
<img :src="url"
alt="">
</div>
</div>
</template>
<script>
import axios from 'axios'
//import * as qiniu from 'qiniu-js'
import ImgShow from './ImgShow.vue'
export default {
name: 'HelloWorld',
data () {
return {
imgValue: {},
url: ''
}
},
components: {
ImgShow
},
methods: {
chooseImg () {
let file = this.$refs.uploadInput.files[0]
console.log(file)
let imgUrl = URL.createObjectURL(file)
console.log(imgUrl)
let title = Math.random() * 10
// this.imgValue = { imgUrl, title }
// this.imgValue.imgUrl = imgUrl
// this.imgValue.title = title
this.$set(this.imgValue, 'imgUrl', imgUrl)
this.$set(this.imgValue, 'title', title)
this.url = imgUrl
}
},
mounted () {
axios.get('/api/getconfig/sodar?sv=200&tid=gpt&tv=2021060901&st=env').then((res) => {
console.log('res', res)
})
// const observable = qiniu.upload(file, key, token, putExtra, config)
//const subscription = observable.subscribe(observer) 上传开始
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.hello {
.wrap {
color: #00ff00;
}
}
.show {
img {
width: 100px;
height: 100px;
}
}
</style>
子组件
<template>
<div>
<h1>图片显示:</h1>
<h3>{{imgValue.title ||` 暂无上传图片标题`}} {{myname}}</h3>
<div class="imgshow">
<img :src="imgValue.imgUrl || `暂无上传图片链接`">
</div>
</div>
</template>
<script>
export default {
name: 'ImgShow',
data () {
return {
}
},
watch: {
'imgValue': {
handler (newName) {
console.log('newName', newName)
},
deep: true,
immediate: true
},
},
computed: {
myname: function () {
return this.imgValue.title + this.imgValue.imgUrl
}
},
props: {
imgValue: {
type: Object,
default () {
return {
}
}
},
url: {
type: String,
default: ''
}
}
}
</script>
<style lang="scss" scoped>
.imgshow {
width: 400px;
height: 400px;
box-sizing: border-box;
border: 1px solid black;
img {
display: flex;
width: 100%;
height: 100%;
}
}
</style>
删掉watch程序也能跑了