欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

vue class、style样式绑定

程序员文章站 2022-05-15 18:22:07
...
  • class对象方式绑定
    <div id="app">
        <div @click="handleDivClick" :class="{activated: isActivated}">
            Hello world
        </div>
    </div>
    
    <script>
		var vm = new Vue({
			el: '#app',
			data:{
				isAcrivated: false
			},
			methods:{
				handleDivClick: function(){
					this.isActivated = !this.isActivated;
				}
			}
		});
	</script>

  • class数组方式绑定
    <div id="app">
        <div @click="handleDivClick" :class="[activated]">
            Hello world
        </div>
    </div>
	
	<script>
		var vm = new Vue({
			el: '#app',
			data:{
				activated: ""
			},
			methods:{
				handleDivClick: function(){
					this.activated = this.activated ==="activated" ? "" : "activated"
				}
			}
		});
	</script>

  • 内联style方式绑定
    <div id="app">
        <div :style="styleObj" @click="handleDivClick">
            Hello world
        </div>
    </div>
	
	<script>
		var vm = new Vue({
			el: "#app",
			data: {
				styleObj:{
					clolor: 'black'
				}
			},
			methods:{
				handleDivClick: function(){
					this.styleObj.color = this.styleObj.color === "black" ? "red" : "black"
				}
			}
		});
	</script>
	
  • 内联style引用数组形式绑定样式
    <div id="app">
        <div :style="[styleObj,{fontSize: '20px'}]" @click="handleDivClick">
            Hello world
        </div>
    </div>
	
	<script>
		var vm = new Vue({
			el: '#app',
			data: {
				styleObj: {
					color: "black"
				}
			},
			methods: {
				handleDivClick: function(){
					this.styleObj.color = this.styleObj.color === "black" ? "red" : "black"
				}
			}
		});
	</script>