Vue.js中对css的操作(修改)具体详解: | 您所在的位置:网站首页 › js改变字体样式的方法 › Vue.js中对css的操作(修改)具体详解: |
使用v-bind:class或者v-bind:style或者直接通过操作dom来对其样式进行更改; 1.v-bind:class || v-bind:style其中v-bind是指令,: 后面的class 和style是参数,而class之后的值在vue的官方文档里被称为'指令预期值'(这个不必深究,反正个人觉得初学知道他叫啥名有啥用就好了)同v-bind的大多数指令(部分特殊指令如V-for除外)一样,除了可以绑定字符串类型的变量外,还支持一个单一的js表达式,也就是说v-bind:class的'指令预期值'除了字符串以外还可以是对象或者数组(‘v-bind:’中的v-bind可省略)。 1.1:对象语法:通过对象来绑定v-bind:class=“{'css类名':控制是否显示(true or false)}” 1.1我的对象更改&&绑定test export default { name: 'mytest', data() { return { display: true } }, mounted() {}, computed: {}, methods:{} } .colordisplay { display: inline; background: red; border: 1px solid blue }如果display为true,那么此时该部分的class就是 class="mycolor colordisplay",通过设置display的值就可以控制colordisplay的显示 如果要设置绑定多个class的话就和正常的对象键值对一样中间用逗号隔开就可以了v-bind:class="{'colordisplay':display,'ispay':pay}" 1.2:内联样式:v-bind:style='mycolor' template 1.2我的样式内联更改&&绑定testdata mypagestyle:{color: 'yellow',background:"blue"}, 1.3:数组语法:也可以通过数组来绑定v-bind:style='[mycolor1,mycolor2]' 1.3我的数组更改&&绑定test然后设置返回的数据为 myarr:{color: 'white'}, myarrtest:{background:'#000',display:'inline'}, 2.计算属性也可以通过计算属性计算(适用于较为复杂判断)样式 2.计算属性判断将计算属性的返回值作为类名,通过判断serd和slid的值来控制样式的显示与否 data() { return {serd:true,slid:true} }, computed: { compuretu: function() { return {compuretu: this.serd && this.slid} } }设置样式 .compuretu{color:white;background: red} 3.操作节点由于vue本身是虚拟dom如果通过document来进行节点样式更改的时候有可能会出现'style' is not definde的错误, 这个问题的解决方式就必须得对vue 的理解要求更高一层了,它可以通过在vue本身的周期mounted函数里用ref和$refs 来获取样式,来完成对其样式的更改:示例如下: 我的test export default { name: 'mytest', data() { return {} }, mounted() {console.log(this.$refs.abc.style.cssText)} }说明: 1.ref被用来给元素(子组件)注册引用信息; 2.vm.$refs 一个对象,持有已注册过 ref 的所有子组件(或HTML元素); 使用:在 HTML元素 中,添加ref属性,然后在JS中通过vm.$refs.属性来获取 上述会将style的内容全部输出(color: green;) 这样的话对其进行更改就可以对相应的属性直接更改(this.$refs.abc.style.color=red) 我的单个class属性的test 1.1我的对象更改&&绑定test 1.3我的样式内联更改&&绑定test 1.3我的数组更改&&绑定test 2.计算属性判断 3.我的dom更改test export default { name: 'mytest', data() { return { serd:true, slid:true, mycss: { color: '' }, mypagestyle:{ color: 'yellow', background:"blue" }, myarr:{ color: 'white' }, myarrtest:{ background:'#000', display:'inline' }, display: true } }, mounted() { console.log(this.$refs.abc.style.cssText) this.$refs.abc.style.color = 'red' //修改属性 this.$refs.abc.style.background = 'black' //新增属性 this.$refs.abc.style.display = 'inline' console.log(111) console.log(this.$refs.abc.style.display) }, computed: { compuretu: function() { return { compuretu: this.serd && this.slid } } }, methods:{ } } .mycss { color: blue } .colordisplay { display: inline; background: red; border: 1px solid blue } .mycolor { color: orange } .computed { border: 1px solid yellow } .compuretu{ color:white; background: red; }当然最后这种方式对于初入门的朋友来讲可能会有点理解不透,所以我更建议大家使用前几种方式 种方式。
欢迎大家评论指正 |
CopyRight 2018-2019 实验室设备网 版权所有 |