以下是一个uniapp使用cookie的简单例子:

  1. 在main.js中设置全局cookie
import Vue from 'vue'
import App from './App'

Vue.config.productionTip = false
Vue.prototype.$cookie = {
  set (name, value, expireDays) {
    const d = new Date()
    d.setTime(d.getTime() + (expireDays * 24 * 60 * 60 * 1000))
    const expires = 'expires=' + d.toUTCString()
    document.cookie = name + '=' + value + ';' + expires + ';path=/'
  },
  get (name) {
    const cookieArr = document.cookie.split(';')
    for (let i = 0; i < cookieArr.length; i++) {
      const cookiePair = cookieArr[i].split('=')
      if (name === cookiePair[0].trim()) {
        return decodeURIComponent(cookiePair[1])
      }
    }
    return null
  },
  delete (name) {
    document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/;'
  }
}

App.mpType = 'app'

const app = new Vue({
  ...App
})
app.$mount()
  1. 在组件中使用cookie
<template>
  <div>
    <p>cookie value: {{ cookieValue }}</p>
    <button @click="setCookie">Set cookie</button>
    <button @click="deleteCookie">Delete cookie</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cookieValue: this.$cookie.get('exampleCookie') || 'undefined'
    }
  },
  methods: {
    setCookie() {
      this.$cookie.set('exampleCookie', 'exampleValue', 1)
      this.cookieValue = this.$cookie.get('exampleCookie')
    },
    deleteCookie() {
      this.$cookie.delete('exampleCookie')
      this.cookieValue = this.$cookie.get('exampleCookie') || 'undefined'
    }
  }
}
</script>

在以上代码中,我们在data中初始化cookieValue为cookie的值,如果cookie不存在,则为undefined。然后我们在setCookie和deleteCookie方法中分别设置和删除cookie,并更新cookieValue的值。

这就是一个简单的uniapp使用cookie的例子。

写一个uniapp 使用cookie的例子

原文地址: https://www.cveoy.top/t/topic/4Ui 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录