我想在 SVG 中畫一條線。這條線必須是垂直的,它的長度必須對應于包含它的 SVG 的高度。由于 SVG 是回應式的,我不能使用像素坐標。相反,我放了一個寬度為 1px 高度為 100% 的矩形。問題是,當我嘗試將它定位在與參考相關的 x 軸上時,Vue.js 給我一個錯誤,(即使它有效:結果)
Error: Invalid value for <rect> attribute x="calc( 100% / 5 * 2 )"
問題來自:
:x="'calc( 100% / ' props.max ' * ' props.x ' )'"
代碼
<script setup lang="ts">
import { defineProps } from "vue";
const props = defineProps<{
x: number,
max: number
}>();
</script>
<template>
<rect :x="'calc( 100% / ' props.max ' * ' props.x ' )'" />
</template>
<style scoped>
rect {
width: 1px;
height: 100%;
stroke: none;
fill: #000000;
}
</style>
我也試過
<script setup lang="ts">
import { defineProps, Ref, ref, onMounted } from "vue";
const props = defineProps<{
x: number,
max: number
}>();
const vertical_line: Ref<HTMLElement | null> = ref(null);
onMounted(() => {
vertical_line.value?.focus();
if (vertical_line.value !== null && typeof vertical_line.value === "object" &&
"setAttribute" in vertical_line.value)
vertical_line.value
.setAttribute("x", "calc( 100% / " props.max " * " props.x " )");
});
</script>
<template>
<rect ref="vertical_line" />
</template>
<style scoped>
rect {
width: 1px;
height: 100%;
stroke: none;
fill: #000000;
}
</style>
uj5u.com熱心網友回復:
看起來你的代碼有效,也許是錯誤的道具?
const { ref } = Vue
const app = Vue.createApp({
setup() {
const x = ref(6)
const max = ref(30)
return { x, max }
}
})
app.component('lineI', {
template: `
<rect :x="'calc( 100% / ' max ' * ' x ' )'" />
`,
props: {
x: { type: Number },
max: { type: Number }
},
})
app.mount('#demo')
rect {
width: 1px;
height: 100%;
stroke: none;
fill: #000000;
}
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
<svg>
<line-i :x="x" :max="max"></line-i>
</svg>
<br>
<input type="number" v-model="x" />
<input type="number" v-model="max" />
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/536433.html
標籤:vue.jssvg
上一篇:在CSS中更改SVG顏色
