在vue3+ts+vite里 <div class="list-item" :style="{ 'background-image': `url('${item.imgUrl}')` }"写url会被转码,怎么办
时间: 2023-11-22 11:54:41 浏览: 47
在 Vue3 中,通过 `:style` 绑定动态样式时,如果属性值是字符串类型,Vue 会自动对其进行 XSS 防御,即将字符串中可能存在的 HTML 字符进行转义,这就导致了你的代码中的 URL 被转码了。
解决这个问题的方式是使用一个计算属性来构造样式对象,并将 URL 作为计算属性的一个属性,例如:
```html
<template>
<div :style="itemStyle"></div>
</template>
<script>
import { computed } from 'vue'
export default {
props: {
item: {
type: Object,
required: true
}
},
setup(props) {
const itemStyle = computed(() => ({
backgroundImage: `url(${props.item.imgUrl})`
}))
return {
itemStyle
}
}
}
</script>
```
这样就可以避免 URL 被转码了。
相关问题
<div class="annual-bar" :style="{ width: item.rate% }"></div> 请指正
这段代码可能存在语法错误,因为在 Vue.js 中,应该使用双括号来绑定动态样式,而不是使用冒号。应该修改为:
```
<div class="annual-bar" :style="{ width: item.rate + '%' }"></div>
```
这样可以将 `item.rate` 的值与百分号连接起来,从而正确设置进度条的宽度。
Vue3+ts+vite 并且使用 <script lang="ts" setup>语法 watch 无效
关于使用 Vue3 + TypeScript + Vite 并且使用 `<script lang="ts" setup>` 语法时 watch 无效的问题,可能是由于使用了 `ref` 或 `reactive` 定义的响应式变量没有正确引用到。在 `<script lang="ts" setup>` 中,响应式变量需要使用 `define` 函数定义,并且在组件中使用时需要使用 `toRef` 或 `toRefs` 函数将其转换成引用变量。
例如,下面是一个定义了响应式变量 `count` 并使用 `watch` 监听其变化的示例:
```vue
<template>
<div>{{ count }}</div>
</template>
<script lang="ts" setup>
import { defineComponent, define } from 'vue'
const state = define({
count: 0
})
const countRef = toRef(state, 'count')
watch(countRef, (newValue, oldValue) => {
console.log('count changed', newValue, oldValue)
})
</script>
```
在上面的示例中,我们使用 `define` 函数定义了响应式变量 `count`,并使用 `toRef` 函数将其转换成引用变量 `countRef`,然后使用 `watch` 监听 `countRef` 的变化。这样就可以正常地监听到 `count` 的变化了。
希望这个解答能够帮到你!