|
| 1 | +# quick example of Vuex and Shiny |
| 2 | +# reference: https://vuex.vuejs.org/guide/ |
| 3 | + |
| 4 | +library(htmltools) |
| 5 | +library(shiny) |
| 6 | + |
| 7 | +vuex <- tags$script(src="https://unpkg.com/vuex@2.5.0/dist/vuex.js") |
| 8 | + |
| 9 | +ui <- tagList( |
| 10 | + html_dependency_vue(offline = FALSE, minified = FALSE), |
| 11 | + tags$head(vuex), |
| 12 | + tags$h1("Shiny with Vue and Vuex"), |
| 13 | + tags$h3('Vue App'), |
| 14 | + tags$div( |
| 15 | + id = "app", |
| 16 | + tags$button(`@click`="increment", "+"), |
| 17 | + tags$button(`@click`="decrement", "-"), |
| 18 | + "{{ count }}" |
| 19 | + ), |
| 20 | + tags$h3("Shiny controls"), |
| 21 | + # add Shiny buttons to demonstrate Shiny to update Vuex state |
| 22 | + actionButton(inputId = "btnIncrement", label="+"), |
| 23 | + actionButton(inputId = "btnDecrement", label="-"), |
| 24 | + tags$script(HTML( |
| 25 | +" |
| 26 | +// first example in Vuex documentation |
| 27 | +Vue.use(Vuex) |
| 28 | +
|
| 29 | +// make sure to call Vue.use(Vuex) if using a module system |
| 30 | +
|
| 31 | +const store = new Vuex.Store({ |
| 32 | + state: { |
| 33 | + count: 0 |
| 34 | + }, |
| 35 | + mutations: { |
| 36 | + increment: state => state.count++, |
| 37 | + decrement: state => state.count-- |
| 38 | + } |
| 39 | +}) |
| 40 | +
|
| 41 | +const app = new Vue({ |
| 42 | + el: '#app', |
| 43 | + computed: { |
| 44 | + count () { |
| 45 | + return store.state.count |
| 46 | + } |
| 47 | + }, |
| 48 | + methods: { |
| 49 | + increment () { |
| 50 | + store.commit('increment') |
| 51 | + }, |
| 52 | + decrement () { |
| 53 | + store.commit('decrement') |
| 54 | + } |
| 55 | + } |
| 56 | +}) |
| 57 | +
|
| 58 | +$(document).on('shiny:sessioninitialized', function() { |
| 59 | + // increment from Shiny custom message |
| 60 | + // chose 'increment' but does not have to match the store mutation name |
| 61 | + Shiny.addCustomMessageHandler('increment', function(msg) { |
| 62 | + store.commit('increment') |
| 63 | + }); |
| 64 | + Shiny.addCustomMessageHandler('decrement', function(msg) { |
| 65 | + store.commit('decrement') |
| 66 | + }); |
| 67 | +}) |
| 68 | +" |
| 69 | + )) |
| 70 | +) |
| 71 | + |
| 72 | +browsable(ui) |
| 73 | + |
| 74 | +server <- function(input, output, session) { |
| 75 | + observeEvent(input$btnIncrement, { |
| 76 | + session$sendCustomMessage("increment", list()) |
| 77 | + }) |
| 78 | + observeEvent(input$btnDecrement, { |
| 79 | + session$sendCustomMessage("decrement", list()) |
| 80 | + }) |
| 81 | +} |
| 82 | + |
| 83 | +shinyApp( |
| 84 | + ui = ui, |
| 85 | + server = server, |
| 86 | + options = list(launch.browser = rstudioapi::viewer) |
| 87 | +) |
0 commit comments