龙空技术网

小程序Kbone开发教程基础篇03-为按钮绑定事件

一叶孤沙 33

前言:

当前你们对“js如何绑定事件”大概比较着重,大家都想要剖析一些“js如何绑定事件”的相关文章。那么小编也在网摘上收集了一些有关“js如何绑定事件””的相关内容,希望小伙伴们能喜欢,咱们一起来学习一下吧!

前言

本节我们为按钮绑定一个点击事件,点击一次修改Text显示数据。

一、基础知识

1.页面渲染

要实现本节需要的功能,需要首先了解Vue的渲染方式,Vue.js的核心是一个允许采用简洁的模板语法来声明式的将数据渲染进DOM的系统。

声明式渲染用法也很简单,html种调用{{ 要渲染的内容 }}即可,这点和小程序原生开发方式一致,都是调用this中数据显示,因此需要在Vue的data()中放置需要渲染的数据内容。

二、示例

1.修改App.vue中核心代码

<template>  <div>    <KView class="view_show">      {{text}}    </KView>    <KButtonArea class="btn_view">        <KButton type="primary" @click='btn_clicked'>中英文切换</KButton>    </KButtonArea>  </div></template><script>export default {  name: 'App',  mounted() {},  data() {    return {      flag:0,      text:"hello world",    }  },  methods: {    btn_clicked() {      if (0 == this.flag)      {        this.text = '你好 世界'        this.flag = 1      }else      {        this.text = "helo world"        this.flag = 0      }    },  },}</script>

按钮中@click='btn_clicked'绑定按钮点击事件函数为btn_clicked,函数中修改需要渲染的数据,默认显示"hello world",点击按钮后变为"你好 世界",在此点击后恢复,如此实现中英文切换数据显示的功能。

2.加载KButton和KView组件

在上述程序中,我们引入了KButton和KView组件,需要在main.mp.js中引入,代码如下:

import Vue from 'vue'import App from './App.vue'import KButton from 'kbone-ui'import KView from 'kbone-ui'export default function createApp() {  const container = document.createElement('div')  container.id = 'app'  document.body.appendChild(container)  Vue.use(KView)  Vue.use(KButton)  return new Vue({    el: '#app',    render: h => h(App)  })}​

调用Vue.use(KButton)、Vue.use(KView)加载

三、运行

修改build/miniprogram.config.js中的appid为自己小程序的appid,projectname自定义。

进入当前文件夹03-btn_event根目录,输入:

npm install npm run mp

然后进入dist/mp路径,输入:

npm install 

接着打开微信开发者工具,加载03-btn_event文件夹,然后工具栏中选择构建npm

点击按钮,切换为中文

作者:小驿

寄语:不要总说我要做什么,而要说我做了什么。

标签: #js如何绑定事件 #vue按钮绑定事件 #vue一个按钮绑定两个事件