如何将 "target" 属性 传递给 Vue.js 组件
How to pass a "target" property to a Vue.js component
如何在我的组件出错时更改 src
属性?
这是模板代码:
<author
v-bind:thumbnail="author.thumbnailUrl"
v-bind:nama="author.id"
v-bind:deskripsi="author.title"
@error="pplUrlAlt"
/>
这是尝试更改 src
错误的方法:
pplUrlAlt(event) {
event.target.thumbnail = "https://images.unsplash.com/photo-1518241353330-0f7941c2d9b5?ixlib=rb-0.3.5&s=c71d179decac2be7a2c39f8252487f97&auto=format&fit=crop&w=1225&q=80"
}
在我切换到组件之前,当我更改损坏的 img
元素的 URL 时它曾经可以工作,但现在它不再工作了。如何使用 props
在我的组件上实现它?
你们很亲近。记住 Vue 是 "data-driven",所以不要试图直接操作 HTML,而是专注于组合你的组件。当您操作组件的数据时,任何更改都会自动反映在您的 HTML 中。
这就是我处理类似问题的方式:
<template>
<author
v-bind:thumbnail="error ? errorThumbnail : author.thumbnailUrl"
v-bind:nama="author.id"
v-bind:deskripsi="author.title"
@error="setError"
/>
</template>
<script>
export default {
data () {
return {
error: false,
errorThumbnail: 'https://images.unsplash.com/photo-1518241353330-0f7941c2d9b5?ixlib=rb-0.3.5&s=c71d179decac2be7a2c39f8252487f97&auto=format&fit=crop&w=1225&q=80'
}
},
methods: {
setError () {
this.error = true
}
}
}
</script>
显然,这是对您的组件可能看起来的简化,但它的要点是:组件应该知道发生错误的事实,并以不同的方式呈现 child 组件,做所以通过改变它的道具价值。这尊重 Vue 的通信范式:children 通过事件与 parents 通信,parents 通过 props 与 children 通信。
如何在我的组件出错时更改 src
属性?
这是模板代码:
<author
v-bind:thumbnail="author.thumbnailUrl"
v-bind:nama="author.id"
v-bind:deskripsi="author.title"
@error="pplUrlAlt"
/>
这是尝试更改 src
错误的方法:
pplUrlAlt(event) {
event.target.thumbnail = "https://images.unsplash.com/photo-1518241353330-0f7941c2d9b5?ixlib=rb-0.3.5&s=c71d179decac2be7a2c39f8252487f97&auto=format&fit=crop&w=1225&q=80"
}
在我切换到组件之前,当我更改损坏的 img
元素的 URL 时它曾经可以工作,但现在它不再工作了。如何使用 props
在我的组件上实现它?
你们很亲近。记住 Vue 是 "data-driven",所以不要试图直接操作 HTML,而是专注于组合你的组件。当您操作组件的数据时,任何更改都会自动反映在您的 HTML 中。
这就是我处理类似问题的方式:
<template>
<author
v-bind:thumbnail="error ? errorThumbnail : author.thumbnailUrl"
v-bind:nama="author.id"
v-bind:deskripsi="author.title"
@error="setError"
/>
</template>
<script>
export default {
data () {
return {
error: false,
errorThumbnail: 'https://images.unsplash.com/photo-1518241353330-0f7941c2d9b5?ixlib=rb-0.3.5&s=c71d179decac2be7a2c39f8252487f97&auto=format&fit=crop&w=1225&q=80'
}
},
methods: {
setError () {
this.error = true
}
}
}
</script>
显然,这是对您的组件可能看起来的简化,但它的要点是:组件应该知道发生错误的事实,并以不同的方式呈现 child 组件,做所以通过改变它的道具价值。这尊重 Vue 的通信范式:children 通过事件与 parents 通信,parents 通过 props 与 children 通信。