(GoRails)使用vue和Vuex管理嵌套的JavaScript评论, 使用组件vue-map-field

时间:2023-03-09 17:01:56
(GoRails)使用vue和Vuex管理嵌套的JavaScript评论, 使用组件vue-map-field

嵌套的JavaScript评论 Widget Models

创建类似https://disqus.com/ 的插件

交互插件:

  • Real time comments:
  • Adapts your site's lokk and feel,可以自定义的调整界面外观
  • Rich media commenting读者可以增加图片和视频。
  • Works everywhere.支持各种设备,语言。

https://gorails.com/系列视频:Embeddable JS widgets.


1.下载模版,按照vue.js

rails new embeded_comment -m template.rb

rails webpacker:install:vue

2. 创建数据库表格Discussion和Comment.

rails g scaffold Discussion url title comments_count:integer

rails g scaffold Comment discussion:references name email body:text ip_address user_agent

rails db:migrate

解释:

url属性,存储当前的讨论版的网址。

然后修改hello_vue为embed

mv app/javascript/packs/{hello_vue,embed}.js  

添加代码:

let url = window.location.href

#encodeURIComponent()用于对输入的URl部分进行转义

fetch(`http://localhost:3000/api/v1/discussions/${encodeURIComponent(url)}`, {
headers: { accept: 'application/json' }
})
.then(response => response.json())
.then(data => console.log(data))

3. 增加路径routes.rb,然后创建一个controller.

mkdir -p app/controllers/api/v1

touch app/controllers/api/v1/disscussions_controller.rb

改为:

  namespace :api do
namespace :v1 do
resources :discussions
end
end resources :discussions do
resources :comments
end

增加一个controller的show方法:

任何如http://localhost/?a=11之类的网址,会启用emben.js中的代码,然后执行show action行为,并转到对应的网页

class Api::V1::DiscussionsController < ApplicationController
def show
@discussion = Discussion.by_url(params[:id])
render "discussions/show"
end
end

在model,增加一个类方法by_url

#model, 增加by_url类方法。一个sanitize URL的方法,只要"/?"或者“/#”前面的URL部分
#http://localhost/?a=11
#http://localhost:3000/disscussions/#a=shanghai
class Discussion < ApplicationRecord
has_many :comments def self.by_url(url)
uri = url.split("?").first
uri = url.split("#").first
uri.sub!(/\/$/, '')
   # 如果comments中存在这个uri则选择它,不存在则创建它。
where(url: uri).first_or_create
end
end

改动:app/views/discussions/index.html.erb

在最后一行添加:

javascript_pack_tag "embed"

遇到一个问题:

NoMethodError in Devise::SessionsController#create

undefined method `current_sign_in_at' for #<User:0x00007fcad84de6f8>

生成User表格时没有使用Trackable下的属性:
      ## Trackable
# t.integer :sign_in_count, default: , null: false
# t.datetime :current_sign_in_at
# t.datetime :last_sign_in_at
# t.string :current_sign_in_ip
# t.string :last_sign_in_ip

2个方法解决:

  • 添加上需要的属性,migration
  • 或者从Devise model中去掉:trackable.

视频2

使用Vuex建立Vue前端和Rails后端的关联

1. 安装Vuex

Vuex是a state management pattern + library。用于Vue.js app。

yarn add vuex

2. 前端vue.js

事件监听:

# embed.js

const event = (typeof Turbolinks == "object" && Turbolinks.supported) ? "turbolinks:load" : "DOMContentLoaded"

document.addEventListener(event, () => {
const el = document.querySelector("#comment")
const app = new Vue({
el,
render: h => h(App)
}) console.log(app)
})

修改app.js

<template>
<div id="comments">
<p>{{ message }}</p>
</div>
</template>

把上一视频的代码移动到store.js中

embed.js载入它。

import store from '../store'

// 使用Vuex关联store.调用store的action中的方法
store.dispatch("loadComments")

解释:Action通过store.dispatch来触发。


几张截图回顾一下Vuex和Vue

1.  比较vue, Vuex实例中的特性:

  • data - state
  • methods - actions/mutations
  • computed - getters

(GoRails)使用vue和Vuex管理嵌套的JavaScript评论, 使用组件vue-map-field

2.Vuex的motion。

  1. axios执行到context.commit,
  2. 执行mutations中的SET_LOADING_STATUS方法,
  3. 然后再对state中的特性进行修改。

(GoRails)使用vue和Vuex管理嵌套的JavaScript评论, 使用组件vue-map-field

3. 执行fetchTodos方法的过程图

  • 首先,执行:commit("SET_LOADING_STATUS", status),  最后State上更新loadingStatus: 'loading'
  • 然后:取数据:axios.get('/api/todos'),
  • 当数据被取回后,执行后面的context.commit。
    • commit('SET_LOADING_STATUS', status),  最后更新loadingStatus: 'notLoading'
    • 最后commit('SET_TODOS', todos), 最后更新State中的todos属性。
  • 最后, 执行this.$store.getters.doneTodo

(GoRails)使用vue和Vuex管理嵌套的JavaScript评论, 使用组件vue-map-field


新建store.js文件:

import Vue from 'vue'
import Vuex from "vuex" Vue.use(Vuex) const store = new Vuex.Store({
state: {
comments: []
}, mutations: {
load(state, comments) {
state.comments = comments
}
}, action: {
// 使用了参数解构。用commit来代替context.commit。
// context其实是一个store实例。
//async异步函数的普通写法:解释见