Vue.js中使用<script setup>后元素选择器失效该如何解决?
问题原因及解决方案
你的代码没效果是因为<script setup>里的代码在组件DOM还没挂载到页面时就执行了,这时候document.querySelector('h1')根本找不到对应的元素,自然无法修改颜色。
下面给你两种可行的解决办法:
方法1:用Vue的生命周期钩子onMounted
onMounted会在组件DOM完全挂载后触发,这时候就能正常选中元素了:
<template> <br><br><br> <h1>Dashboard Page Here</h1> </template> <script> export default { name: "xxxView", } </script> <script setup> import { onMounted } from 'vue' onMounted(() => { const color = document.querySelector('h1'); color.style.color = 'green'; }) </script> <style scoped> </style>
方法2:用Vue的ref绑定元素(推荐)
Vue更推荐通过ref直接获取组件内的DOM元素,不用全局查找,更符合Vue的开发逻辑:
<template> <br><br><br> <h1 ref="titleRef">Dashboard Page Here</h1> </template> <script> export default { name: "xxxView", } </script> <script setup> import { ref, onMounted } from 'vue' const titleRef = ref(null) onMounted(() => { titleRef.value.style.color = 'green'; }) </script> <style scoped> </style>
如果需要让颜色支持响应式切换,还可以结合按钮点击等场景动态修改:
<template> <br><br><br> <h1 ref="titleRef">Dashboard Page Here</h1> <button @click="toggleColor">切换颜色</button> </template> <script setup> import { ref } from 'vue' const titleRef = ref(null) let isGreen = true const toggleColor = () => { isGreen = !isGreen titleRef.value.style.color = isGreen ? 'green' : 'red' } // 初始化颜色 titleRef.value?.style.color = 'green' </script>
内容的提问来源于stack exchange,提问作者Farhan Ersavan
相关产品推荐
相关产品推荐

