How to dynamically add class attribute in WeChat applet

In the WeChat applet, you can use the setData method to dynamically add classes. First, in the js file of your page, define a variable to store the class that needs to be added dynamically, for example:

data: {
  dynamicClass: ''
}

Then, where the class needs to be added dynamically, use the setData method to update the value of dynamicClass, for example:

// 假设你想在点击按钮时动态添加class
onTapButton: function() {
  this.setData({
    dynamicClass: 'new-class'
  });
}

Finally, in your wxml file, add the class using dynamic binding, for example:

<view class="{
   
   {dynamicClass}}">这是一个视图</view>

This way, when you click the button, the view's class will dynamically change to new-class.

Dynamically add class to component

.wxml

<view class="toast {
    
    {closeToast}}"> </view>

First, in the wxml file, <view>there is a tag with two class attributes: toastand { {closeToast}}. Here toastis a static class, { {closeToast}}but a dynamic class, its value will closeToastchange dynamically according to the value of the attribute.

.js

Component({
    
    
  options: {
    
    
    addGlobalClass: true
  },
  properties: {
    
    
    closeToast:" "
  },
  methods: {
    
       
    close() {
    
    	// 定义取消
      this.setData({
    
    closeToast:"toast show"})
    }
  }
})

In the js file, this component is Componentdefined using a function. In options, it is set addGlobalClass: true, which means that the component's style will inherit the global style.

In properties, an attribute is defined closeToastwhose type is string and whose initial value is an empty string.

In methods, a method is defined close(). When this method is called, the value of the attribute will be setDataset closeToastto "toast show", which will trigger the update of the dynamic class.

To sum up, the function of this code is: when close()the method of the component is called, closeToastthe value of the attribute will be set to "toast show", thus dynamically <view>adding a class named "toast show"class to the label.

Guess you like

Origin blog.csdn.net/wbskb/article/details/132390520