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: toast
and {
{closeToast}}
. Here toast
is a static class, {
{closeToast}}
but a dynamic class, its value will closeToast
change 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 Component
defined 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 closeToast
whose 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 setData
set closeToast
to "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, closeToast
the value of the attribute will be set to "toast show"
, thus dynamically <view>
adding a class named "toast show"
class to the label.