admin 管理员组

文章数量: 1087649

Vue动态绑样式

一般会配合三元表达式进行动态的判断如过比较简单的可以直接在style上直接写属性判断

v-bind:style={color:myColor,fontSize:fontSize + 'px'}

一  什么是vue 动态绑定    一般 用 v-bind 来表示进行动态的绑定

   

示例: v-bind:style     但是我们一般都使用缩写形式:style 

二、动态绑定的方式

1.对象形式

代码如下(示例):

v-bind:style="{name,age}"

2.数组形式

代码如下(示例):
 

v-bind:style="[name,age]"

2.一般 如果需要计算的建议这样写(calc()) 还有这样可控性大大提高
 

<template><div :style="name"> {{age}}</div><HelloWorld msg="Welcome to Your Vue.js App"/>
</template><script>
// @ is an alias to /src
import HelloWorld from '@/components/HelloWorld.vue'
// import  {ref,reactive,toRefs,computed,onBeforeMount,onMounted,onBeforeUnmount,onUnmounted} from 'vue'
export default {name: 'Home',components:{HelloWorld},data(){return {name:{height:'20px',width:'20px',color:'red'}}},watch:{},}}
</script>
<style>
.home{height: 100%;width: 100%;}
</style>
​

   配合三元表达式动态处理连续写法

<template><div :style="{color:name ='张三' ? 'red' : name = '李四' ? 'blue' : '' }"> {{age}}</div><HelloWorld msg="Welcome to Your Vue.js App"/>
</template><script>
// @ is an alias to /src
import HelloWorld from '@/components/HelloWorld.vue'
// import  {ref,reactive,toRefs,computed,onBeforeMount,onMounted,onBeforeUnmount,onUnmounted} from 'vue'
export default {name: 'Home',components:{HelloWorld},data(){return {name:'李四'}},watch:{},setup(){//   let name = ref("ddd")//   let prope = reactive({//        age:20//   })// let  xingming  = computed( () =>{//            return  name.value// })//   let chenname = function () {//      console.log("出发了")//            name.value= name.value+"1"//   }////   //卸载后//   onUnmounted( () => {//       document.removeEventListener('mousemove')//   })//   //挂载后//   onMounted(() =>{//         document.addEventListener('mousemove',()=>{//              console.log("move")////       })//   })//   //挂在后//   onBeforeUnmount( (////   ) =>{})////   onBeforeMount(()=>{})//   return {//        name,//       chenname,//       prope,//       xingming,//       ...(toRefs(prope))////  };}// components: {//   HelloWorld// }
}
</script>
<style>
.home{height: 100%;width: 100%;}
</style>

不使用:v-bind 实现动态绑定 ``  反引号

   style=`color:${ mycolor }`

本文标签: Vue动态绑样式